ValueError: setting an array element with a sequence when array is not a sequence

混江龙づ霸主 提交于 2021-01-29 01:30:19

问题


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

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

For reference: "1.jpg" is the image shown below

1

Any leads as to how to fix this error would be greatly appreciated!


回答1:


Each "pixel" here have one value. crop_img = [[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) ]

Although you might as well start off with a numpy array with shape 377,377, 3 instead of converting it afterwards.




回答2:


                crop_img[col][row] = [0,0,0]

Is this supposed to be an RGB value? crop_img starts as a list of 377 elements, each of which is a list of 377 elements, each element of which is the integer 255. This line replaces a 255 with a list. It's not clear whether you want 2-dimensional nesting, which is the way you're initializing crop_img, or 3-dimensional nesting, which is what this line would suggest. Pick the one that's correct for your application and stick with it.



来源:https://stackoverflow.com/questions/21133214/valueerror-setting-an-array-element-with-a-sequence-when-array-is-not-a-sequenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!