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
Any leads as to how to fix this error would be greatly appreciated!