Getting coordinates of the edges of the box inside the image in python

Viewed 25

I am trying to get the coordinates [x, y] of the edges of the box in the image attached.

This is the image I am using to get the edge coordinates:

image

I am finding difficulty in getting. Anybody, please help me in getting the coordinates.

image= Image.open(r"C:/Users/LikithP/OneDrive - Ennoventure Inc/Documents/Projects/Gold_Bar/finding_corner_points/mask_images/enc-1.jpg")

numpy_data=np.array(image)
img = numpy_data[:,:,0]
_, th = cv2.threshold(img, img.mean(), 255, cv2.THRESH_BINARY_INV)
th = cv2.morphologyEx(th, cv2.MORPH_CLOSE, np.ones((3,3)))

x1, y1 = 0, 0
y2, x2 = th.shape[:2]

while np.all(th[:,x1]==255):
    x1 = x1+1
while np.all(th[:,x2-1]==255):
    x2 = x2-1
while np.all(th[y1,:]==255):
    y1 = y1+1
while np.all(th[y2-1,:]==255):
    y2 = y2-1
cv2.imwrite("image.jpg",image[y1:y2-1,x1:x2-1])

This is giving error as TypeError: 'JpegImageFile' object is not subscriptable

1 Answers

Try referencing img instead of image. You are initially trying to index the Image object rather than the actual image data which is in img:

cv2.imwrite("image.jpg", img[y1:y2-1,x1:x2-1])
Related