Search code examples
pythonopencvbounding-box

Trying to determine the co-ordinates of the bounding box in the image and crop it further on


I'm trying to get the co-ordinates of the bbox in the image and crop that area from the image. I'm a newbie with opencv and python

I tried getting the list of the co-ordinates in a list and trying to pass it in. It gives an error of "SystemError: tile cannot extend outside image". I looked for answers in this regard but couldn't understand it.

import numpy as np
import imutils, cv2
import o
from PIL import Image

original_image = cv2.imread("04239713_02718309.tiff")
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 120, 255, 1)

#cv2.imshow("edged", edged)

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

checkbox_contours = []

threshold_max_area = 3000
threshold_min_area = 375
contour_image = edged.copy()
cood=[]
allcoord=[]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.035 * peri, True)
    x=0
    y=0
    w=0
    h=0

    (x, y, w, h) = cv2.boundingRect(approx)
    aspect_ratio = w / float(h)
    area = cv2.contourArea(c) 
    if area < threshold_max_area and area > threshold_min_area and (aspect_ratio >= 0.9 and aspect_ratio <= 1):
        cv2.drawContours(original_image,[c], 0, (0,255,0), 3)
        #print(x,y,w,h)
        temp=(x,y,w,h)



        cood.append(temp)


        checkbox_contours.append(c)
        allcoord.append(cood)
print("cood",len(cood))        
#print("allcoords",allcoord)
#print(allcoord)
print('checkbox_contours', len(checkbox_contours))
cv2.imwrite("peternass1.png", original_image)
print(cood)
org_image ='04239713_02718309.tiff'
for i, n in enumerate(cood):
    image_obj = Image.open(org_image)
    cropped_image = image_obj.crop(n)
    os.system("{}.png".format(i))
    cropped_image.save('Cro_{}.png'.format(i), 'png')

Solution

  • I'm using opencv 4.0 here

    You find the contours with

    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    

    You can draw a bounding box around the first contour

    cnt = contours[0]
    x,y,w,h = cv2.boundingRect(cnt)
    

    x,y are the left top coordinates of the bounding

    w is the width(x coordinate value),h is the height(y coordinate value)

    let say your original image was

    img = cv2.imread('myimage.jpg')
    

    you can crop it using

    #x1,y1 = x,y(left top corner) and x2,y2 = x+w,y+h(right bottom corner)
    selected_roi = img[y1:y2,x1:x2]
    

    Image ROI