Python-OpenCV cv2 OpenCV错误:断言失败

时间:2017-12-06 23:08:55

标签: python-3.x opencv

我尝试使用openCV在python中创建图像。我列出了一个列表,每个列表有16个数字,从0到255(16个列表)。然后我在numpy ndarray中转换大列表,并尝试使用cv2.imwrite()将其写入图像。这是我的代码:

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)

它运行良好,直到最后一行。然后它给了我这个错误:

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_

一般来说,我是一名初学者,所以我可能会发现一些非常明显的错误,但我还没有找到类似的错误问题。

1 个答案:

答案 0 :(得分:0)

你正在做这个非常微小的错误。从以下工作代码中找出 -

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)

检查编辑提示。