【问题标题】:What is the reason for this error? (-215:Assertion failed) !_src.empty() in function 'cvtColor' [duplicate]这个错误的原因是什么? (-215:断言失败)函数'cvtColor'中的!_src.empty()[重复]
【发布时间】:2021-08-08 00:58:16
【问题描述】:
OpenCV(4.1.2) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'. 

这里出错的原因是什么?

    import tensorflow as tf
    from keras.layers import Conv2D, Input, ZeroPadding2D, BatchNormalization, Activation, MaxPooling2D, Flatten, Dense
    from keras.models import Model, load_model
    from keras.callbacks import TensorBoard, ModelCheckpoint
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import f1_score
    from sklearn.utils import shuffle
    import cv2
    import imutils
    import numpy as np
    import matplotlib.pyplot as plt
    import time
    from os import listdir
    import pickle
    import joblib
    
    %matplotlib inline
    
    
    
    def crop_brain_contour(image, plot=False):
        
        grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        grayscale = cv2.GaussianBlur(grayscale, (5, 5), 0)
        threshold_image = cv2.threshold(grayscale, 45, 255, cv2.THRESH_BINARY)[1]
        threshold_image = cv2.erode(threshold_image, None, iterations=2)
        threshold_image = cv2.dilate(threshold_image, None, iterations=2)
    
        contour = cv2.findContours(threshold_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        contour = imutils.grab_contours(contour)
        c = max(contour, key=cv2.contourArea)
        
        extreme_pnts_Left = tuple(c[c[:, :, 0].argmin()][0])
        extreme_pnts_Right = tuple(c[c[:, :, 0].argmax()][0])
        extreme_pnts_Top = tuple(c[c[:, :, 1].argmin()][0])
        extreme_pnts_Bot = tuple(c[c[:, :, 1].argmax()][0])
        
        new_image = image[extreme_pnts_Top[1]:extreme_pnts_Bot[1], extreme_pnts_Left[0]:extreme_pnts_Right[0]]            
    
        if plot:
            plt.figure()
    
            plt.subplot(1, 2, 1)
            plt.imshow(image)
            
            plt.tick_params(axis='both', which='both', 
                            top=False, bottom=False, left=False, right=False,
                            labelbottom=False, labeltop=False, labelleft=False, labelright=False)
            
            plt.title('Original Image')
                
            plt.subplot(1, 2, 2)
            plt.imshow(new_image)
    
            plt.tick_params(axis='both', which='both', 
                            top=False, bottom=False, left=False, right=False,
                            labelbottom=False, labeltop=False, labelleft=False, labelright=False)
    
            plt.title('Cropped Image')
            
            plt.show()
        
        return new_image
    
    
    
    
    ex_img = cv2.imread('/content/drive/MyDrive/Alzheimer/Alzheimer_s Dataset/train/MildDemented/mildDem0.jpg')
    ex_new_img = crop_brain_contour(ex_img, True)
    
    
    
    
    ex_img = cv2.imread('/content/drive/MyDrive/Alzheimer/Alzheimer_s Dataset/train/MildDemented/mildDem0.jpg')
    ex_new_img = crop_brain_contour(ex_img, True)
    
    
    
    def load_data(dir_list, image_size):
        
    
        X = []
        y = []
        image_width, image_height = image_size
        
        for directory in dir_list:
            for filename in listdir(directory):
                print(directory + '/' + filename)
    
                image = cv2.imread(directory + '/' + filename)
                
                image = crop_brain_contour(image, plot=False)
    
    
                image = image / 255.
    
                X.append(image)
    
                if directory[-3:] == 'train':
                    y.append([1])
                else:
                    y.append([0])
                    
        X = np.array(X)
        y = np.array(y)
        
        X, y = shuffle(X, y)
        
        print(f'Number of examples is: {len(X)}')
        print(f'X shape is: {X.shape}')
        print(f'y shape is: {y.shape}')
        
        return X, y
    
    
    
    
    Alzheimer_s_Dataset = '/content/drive/MyDrive/Alzheimer/Alzheimer_s Dataset/'
    
    Alzheimer_s_Dataset_train = Alzheimer_s_Dataset + 'train' 
    Alzheimer_s_Dataset_test = Alzheimer_s_Dataset + 'test'
    
    IMG_WIDTH, IMG_HEIGHT = (128, 128)
    #loading dataset
    X, y = load_data([Alzheimer_s_Dataset_train, Alzheimer_s_Dataset_test], (IMG_WIDTH, IMG_HEIGHT))

在此之后它显示 cvtColor 错误。如果有人知道原因以及如何解决,请告诉我?

【问题讨论】:

  • 这能回答你的问题吗? OpenCV !_src.empty() in function 'cvtColor' error
  • imread() 在文件不存在时不会引发错误,但它会给出None,您必须在尝试修改图像之前检查是否收到None
  • 不,我只有在尝试加载数据集时才收到错误。

标签: python opencv keras google-colaboratory cv2


【解决方案1】:
  • 当函数处理空输入时会发生此错误,可能是因为输入没有正确输入。尝试打印图像并检查它是否不是空值。
  • 在调用crop_brain_contour 函数的加载数据函数中,确保正确传递图像的目录。
  • 尝试修改您的代码,甚至包括图像的扩展名,并确保输入正确的目录。尝试将您的代码更改为: image = cv2.imread(directory + '/' + filename + 'extension_of_the_image')

【讨论】:

  • 我试过这样做,但还是不行
  • print(image)crop_brain_contour 函数的第一行并让我知道输出。
  • 除了在输出中打印数组之外,它什么也没做。
  • [colab.research.google.com/drive/…这里是代码链接
  • colab 文件是私有的。请授予对 colab 文件的访问权限。
【解决方案2】:

当您尝试对空图像使用 cv2.cvtColor() 方法时,您会收到错误消息。观察:

>>> import cv2
>>> import numpy as np
>>> img = np.uint8([])
>>> img
array([], dtype=uint8)
>>> cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.5.1) /tmp/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

>>> 

您的代码中出现空图像的可能原因是您在不存在的路径上使用了cv2.imread() 方法。确保您的路径定义正确,其中一种方法是使用os.path.exists() 方法:

>>> import os
>>> path = "Folder/images/1.png"
>>> if os.path.exists(path):
...     img = cv2.imread(path)
... else:
...     print("Path does not exist:", path)
... 
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2021-12-19
    • 2022-01-10
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多