错误: OpenCV(4.1.2) (-215:断言失败) image.channels() == 1 ||图像通道() == 3 ||image.channels() == 4 in 函数 'cv



我在python 3.7中使用openCV(4.1.2(在windows 7中将我的照片处理为MNIST格式。

首先,我想将照片的大小调整为28*28,然后将其转换为灰度。

最后,我想存储转换后的照片。

我使用以下代码:

def resize(img):
img = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
h = img.shape[0]
w = img.shape[1]
p = max(h,w)/28
if h > w:
resize_h = 28
resize_w = w/p
else:
resize_w = 28
resize_h = h/p    
img_resized = cv.resize(img, (int(resize_h), int(resize_w)), interpolation = cv.INTER_AREA)    
img_resized = cv.resize(img, (28, 28), interpolation = cv.INTER_AREA)
return img_resized    
def load_data(path):       
idx = 0      
total_imgs = len([img_name for img_name in os.listdir(path) if img_name.endswith('.PNG')])
data = np.zeros((total_imgs,28,28), dtype=np.uint8)       
for img_name in os.listdir(path):       
if not img_name.endswith('.PNG'):
continue    
img_path = os.path.join(path, img_name)
img = cv.imread(img_path)            
resized_img = resize(img)   
data[idx, :]=resized_img  
idx+=1      
return  data     
data = load_data('D:\EPS_projects\AI\2_CV\cifar-10\img\0')
cv.imwrite("D:\EPS_projects\AI\2_CV\MNIST\work200306\0\1_im.PNG", data);

但当我运行这段代码时,当我试图使用cv.imwrite保存转换后的照片时,在最后一行出现了错误。

错误为:error: OpenCV(4.1.2) C:projectsopencv-pythonopencvmodulesimgcodecssrcloadsave.cpp:668: error: (-215:Assertion failed) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function 'cv::imwrite_'

如何解决我的问题?

(-215:Assertion failed) image.channels() == 1 || image.channels() == 3 || image.channels() == 4

括号后的表达式是断言表达式,即必须为true才能继续。

这个特定的表达式表示,您传递的数据必须具有单色图像(1个通道(、彩色图像(3个通道(或带alpha通道的彩色图像(4个通道(的形状。因此,请相应地修改您正在传递的数据的形状。

最新更新