错误:OpenCV(4.1.2)(-215:声明失败)image.channels()== 1 || image.channels()== 3 || image.channels()== 4在函数'cv :: imwrite _'

问题描述 投票:-1回答:1

我在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:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:668: error: (-215:Assertion failed) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function 'cv::imwrite_'

如何解决我的问题?

python opencv mnist
1个回答
0
投票
(-215:Assertion failed) image.channels() == 1 || image.channels() == 3 || image.channels() == 4

方括号后的表达式是断言表达式-即必须为真才能继续进行的表达式。

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

© www.soinside.com 2019 - 2024. All rights reserved.