ValueError:当数组不是序列时使用序列设置数组元素 [英] ValueError: setting an array element with a sequence when array is not a sequence
问题描述
您好,这段代码旨在存储用 open cv 绘制的矩形的坐标,并将结果编译为单个图像.
Hello this code is intended to store the coordinates of rectangles drawn with open cv and compile the results into a single image.
import numpy as np
import cv2
im = cv2.imread('1.jpg')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
squares = []
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28 and h<34:
rect = (cv2.rectangle(im,(x,y),(x+w,y+h),(255,255,255),3))
squares.append(cv2.boundingRect(cnt))
cv2.imwrite('norm1.jpg',im)
crop_img = [[255 for x in xrange(377)] for x in xrange(377) ]
for s in squares:
s = squares[0]
x = s[0]
y = s[1]
w = s[2]
h = s[3]
img = im[y:y+h,x:x+w]
for col in range(y,y+h):
for row in range(x,x+w):
if img[col - y][row - x].tolist() == [0,0,0]:
crop_img[col][row] = [0,0,0]
cv2.imwrite("cropped.jpg", np.array(crop_img))
但是,它抛出此错误消息
However, it throws this error message
File "C:\Users\Program\Desktop\new 1.py", line 43, in <module>
cv2.imwrite("cropped.jpg", np.array(crop_img))
ValueError: setting an array element with a sequence
我已经读到这可能是由不均匀"矩阵引起的,但经过几轮测试后,我确认它确实是一个正方形 377 x 377 矩阵
I have read that this can be caused by an "uneven" matrix but after several rounds of testing I have confirmed that it is indeed a square 377 x 377 matrix
供参考:1.jpg"为下图
For reference: "1.jpg" is the image shown below
任何有关如何修复此错误的线索将不胜感激!
Any leads as to how to fix this error would be greatly appreciated!
推荐答案
这里的每个像素"都有一个值.crop_img = [[255 for x in xrange(377)] for x in xrange(377)]
Each "pixel" here have one value. crop_img = [[255 for x in xrange(377)] for x in xrange(377) ]
但稍后您将其中一些设置为包含 3 个值的列表.这就是问题所在.
我认为这应该可以解决它:crop_img = [[[255, 255, 255] for x in xrange(377)] for x in xrange(377) ]
But later you're setting some of them to a list of 3 values. That's the problem.
This should fix it i think:
crop_img = [[[255, 255, 255] for x in xrange(377)] for x in xrange(377) ]
虽然你最好从一个形状为 377,377, 3 的 numpy 数组开始,而不是之后再转换它.
Although you might as well start off with a numpy array with shape 377,377, 3 instead of converting it afterwards.
这篇关于ValueError:当数组不是序列时使用序列设置数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!