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错误。如果有人知道原因以及如何解决,请告诉我?
当您试图在空图像上使用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)
...
>>>
- 当函数处理null输入时会发生此错误,可能是因为输入未正确输入。请尝试打印图像并检查它是否为空值
- 在调用
crop_brain_contour
函数的加载数据函数中,请确保正确传递映像的目录 - 尝试修改您的代码,甚至包括图像的扩展名,并确保输入正确的目录。尝试将代码更改为:
image = cv2.imread(directory + '/' + filename + 'extension_of_the_image')