How to merge detected boxes with opencv?

136 Views Asked by At

I wrote a code that can detect the differences between two pages, but I want the boxes close to each other to appear as a single box,I want to see it in the form of the purple box in the picture I added.

How can I do this, I have the coordinates of all the boxes?

Detected Pages

The other scenario; enter image description here

from calendar import c
import cv2
import imutils
import numpy as np
from skimage.metrics import structural_similarity as ssim

img1 = cv2.imread(r'C:\deneme\19371\19371-028.jpg')
img2 = cv2.imread(r'C:\deneme\19371_Ogretmen\19371_Ogretmen-028.jpg')
print(img1.shape)
img_height = img1.shape[0]

gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)


(similar, diff) = ssim(gray1, gray2, full=True)

print("Level of similarity : {}".format(similar))

diff = (diff*255).astype("uint8")
#cv2.imshow(diff)

thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
#cv2.imshow(thresh)


contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)


counter=0


for contour in contours:

    if cv2.contourArea(contour) > 10:
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(img1, (x, y), (x+w, y+h), (0,0,255), 2)
        cv2.putText(img1,str(counter),(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)
        cv2.rectangle(img2, (x, y), (x+w, y+h), (0,0,255), 2)
        cv2.putText(img2,str(counter),(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)
        counter=counter+1
        print("{}".format(counter),x,y,w,h)
     

x = np.zeros((img_height,10,3), np.uint8)
result = np.hstack((img1, x, img2))
#cv2.imshow("Result",result)
cv2.imwrite('cikti.jpg',result)
print(len(liste))
#cv2.waitKey(0)
#cv2.destroyAllWindows()

Image Source => https://drive.google.com/drive/folders/1bsmp7WePSngmygrOYmo7NxbrYUmVLDok?usp=sharing

0

There are 0 best solutions below