2

I'm trying to create an image in python using openCV. I make a list of lists, each list having 16 numbers, from 0 to 255 (16 lists). Then I convert the big list in a numpy ndarray, and try to write that into an image using cv2.imwrite(). This is my code:

import cv2 import numpy as np colours = [] numbers = [] a=0 for i in range(256): numbers.append(a) a+=1 for x in range(16): new_list = [numbers[16*x:16*x+16]] colours.append(new_list) col = np.asarray(colours) new_image = cv2.imwrite("rainbow.png",col) 

It runs well until the last line. Then it gives me this error:

OpenCV Error: Assertion failed (image.channels() == 1 || image.channels() == 3 || image.channels() == 4) in cv::imwrite_, file C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp, line 600 Traceback (most recent call last): File "kormou.py", line 16, in <module> new_image = cv2.imwrite("rainbow.png",col) cv2.error: C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:600: error: (-215) image.channels() == 1 || image.channels() == 3 || image.channels() == 4 in function cv::imwrite_ 

In generally I'm a beginner so it may be something very obvious which I'm missing but I haven't been able to find similar error question here.

2
  • 1
    It's saying that the assertion that "image.channels() == 1 || image.channels() == 3 || image.channels() == 4" has failed in the imwrite function. So, how many channels does the image have? Commented Dec 6, 2017 at 23:16
  • 1
    You're feeding a 16 channel "image" to imwrite. As the docs state, it only supports 1,3 or 4 channels. Also, it doesn't return an image, but a boolean, so the variable name new_image is rather misleading. Commented Dec 6, 2017 at 23:17

1 Answer 1

3

There is this very minute mistake you are doing. Figure out from the following working code -

import cv2 import numpy as np colours = [] numbers = [] a=0 for i in range(256): numbers.append(a) a+=1 for x in range(16): new_list = numbers[16*x:16*x+16] colours.append(new_list) print colours col = np.asarray(colours) new_image_flag = cv2.imwrite("rain.png",col) 

Check edit for hint.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.