How to read and display images from a Drive directory using OpenCV and numpy?

Viewed 638

I'm trying to read an image from a directory on my drive, for this I use OpenCV, I convert the image to a numpy array of 32-bit floats and then display it, the problem I have is that the image is not displayed. The images correspond to chest X-rays and I'm working at Google Colab.

import matplotlib.pyplot as plt
import cv2
from skimage import transform
import numpy as np

img_r = cv2.imread('/content/drive/MyDrive/images/T-NORMAL- (3).jpeg')

img1 = np.array(img_r).astype('float32')/255
img2 = transform.resize(img1, (150, 150, 3))

plt.imshow(img2)

This is the result obtained from the first code. As seen, it is as if the image was not being well-read.

Thinking that I was not accessing the directory correctly, I used the os.listdir method, as shown in the following code, the images are not shown anyway.

import matplotlib.pyplot as plt
import os
import numpy as np
import cv2
from skimage import transform


items = os.listdir('/content/drive/MyDrive/imagenes')
print (items)

for each_image in items:
  if each_image.endswith(".jpeg"):
   print (each_image)
   full_path = "/content/drive/MyDrive/imagenes" + each_image
   print (full_path)
   image = cv2.imread(full_path)
   img1 = np.array(image).astype('float32')/255
   img2 = transform.resize(img1, (150, 150, 3))

plt.imshow(img2)

This is what is displayed as a result of the second code.

I hope someone can help me. Thanks in advance.

1 Answers

Let me know if this works

import cv2

img_r = cv2.imread('/content/drive/MyDrive/images/T-NORMAL- (3).jpeg')

#to resize image
reimg_r = cv2.resize(img_r,(150,150))

cv2.imshow('xrays',reimg_r)
cv2.waitKey(0)
cv2.destroyAllWindows()
Related