Home > Back-end >  Matlotlib Can Read the Image but OpenCV Cant?
Matlotlib Can Read the Image but OpenCV Cant?

Time:04-24

I am working on Google Colab and trying to read images from Drive. I am working on cat-dog dataset. I get the error AttributeError: 'NoneType' object has no attribute 'shape'. I suspected if the image does not exist in the given path and checked. It exists, however I cant read it. Here is the code below. I am suspected if using Drive causes that issue, or maybe the image shape is too small(4.31 KB). I can read the image by using Matplotlib. Any help is highly appreciated.

for dir1 in os.listdir(train_data_dir):
  for file in os.listdir(os.path.join(train_data_dir, dir1)):
    image_path= os.path.join(train_data_dir, dir1,  file)
    image= cv2.imread( image_path, cv2.COLOR_BGR2RGB)
    if (image.shape[-1] != 3 ):
        print(image.shape)

I checked by opening Drive folder, also used the code snippet below. The file exists.

import os.path
from os import path
path.exists('cat-dog-splitted/train/Dog/9188.jpg')

CodePudding user response:

I solved the issue, however could not understand the reason behind it. I used try catch to avoid the images that give error.

try:
    image=cv2.resize(image, (img_height, img_width),interpolation = cv2.INTER_AREA)
except:
    continue

CodePudding user response:

Check this !

for dir1 in os.listdir(train_data_dir):
  for file in os.listdir(os.path.join(train_data_dir, dir1)):
    image_path= os.path.join(train_data_dir, dir1,  file)
    image= cv2.imread( image_path, cv2.COLOR_BGR2RGB)
    if (image.shape[-1] != 3 ):
        print(image.shape[0])
  • Related