-1

I use openCV(4.1.2) in python 3.7 to process my photos to MNIST format in windows 7.

First I want to resize my photo to 28*28, and then convert it to grayscale.

Finally, I want to store the converted photos.

I use the following code:

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);

But when I run this piece of code, error occurs at the last line when I tried to use cv.imwrite to save the converted photos.

The error is: 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_'

How to solve my problem?

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Django
  • 99
  • 1
  • 1
  • 11
  • 1
    Does this answer your question? [Python-OpenCV cv2 OpenCV Error: Assertion failed](https://stackoverflow.com/questions/47685019/python-opencv-cv2-opencv-error-assertion-failed) – ilke444 Mar 25 '20 at 04:34

1 Answers1

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

The expression after the brackets is the assertion expression -- i.e. an expression that must be true to be able to proceed.

This specific expression says that the data that you are passing must have the shape of either a monochrome image (1 channel), a color image (3 channels) or a color image with alpha-channel (4 channels). So fix the shape of the data that you are passing accordingly.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • How to fix the shape of data in my case? – Django Mar 25 '20 at 04:32
  • @Django [The 3rd dimension of the array is the number of channels](https://stackoverflow.com/questions/19062875/how-to-get-the-number-of-channels-from-an-image-in-opencv-2). – ivan_pozdeev Mar 25 '20 at 04:57