Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
add comment
                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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.