-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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How to fix the shape of data in my case?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.