Thodoris Roumanis
Thodoris Roumanis

Reputation: 41

Python-OpenCV cv2 OpenCV Error: Assertion failed

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.

Upvotes: 2

Views: 5081

Answers (1)

I.Newton
I.Newton

Reputation: 1783

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.

Upvotes: 3

Related Questions