Hasan Iqbal
Hasan Iqbal

Reputation: 173

Is there any way to get 4 coordinate points of bounding rectangle of two separate contours in opencv python?

I have picture like this below: Original Picture

Now, I want to get four coordinate points for perspective warp like this below: Desired Picture

Here, I have two questions: 1. How can I get 4 coordinate points for perspective warp? 2. How can I pin point this location in the whole image as if we use contours, there are many lines/rectangles etc.

Upvotes: 4

Views: 1978

Answers (1)

Zhubei Federer
Zhubei Federer

Reputation: 1270

first found contours that hierarchy layer > 2,and you cad get contours as below: enter image description here second,those separate contours has special perimeter/area ratio,so found contours that area between 3000~4000 and perimeter between 800~1000: enter image description here finally,found min max of two contours ,and you can get result rectangle: enter image description here here's my sample code:

import cv2
import numpy as np
def found_by_hierarchy(contours, hierarchy,H):
    list = []
    for i in range(len(contours)):
       k = i
       c = 0
       while hierarchy[k][3] != -1:
           k = hierarchy[k][3]
           c = c + 1
       if c > H:
           list.append(i)
    return list
def minmax(list,min_x,max_x,min_y,max_y):
    for i in list:
        min_x=i[0][0] if i[0][0] < min_x else min_x
        max_x=i[0][0] if i[0][0] > max_x else max_x
        min_y=i[0][1] if i[0][1] < min_y else min_y
        max_y=i[0][1] if i[0][1] > max_y else max_y
    return min_x,max_x,min_y,max_y
img = cv2.imread("123.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gb = cv2.GaussianBlur(img_gray, (5, 5), 0)
edges = cv2.Canny(img_gb, 50 , 200)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

min_x,max_x,min_y,max_y = 99999,-1,99999,-1
for i in found_by_hierarchy(contours, hierarchy[0], 0):
    area = cv2.contourArea(contours[i])
    perimeter = cv2.arcLength(contours[i], True)
    if int(area) in range(3000,4000) and int(perimeter) in range(800,1000):
        min_x,max_x,min_y,max_y=minmax(contours[i],min_x,max_x,min_y,max_y)
cv2.rectangle(img, (min_x,min_y), (max_x,max_y), (0, 0, 255), 2)
draw_img = cv2.resize(img, (1500, 1500))   
cv2.imshow("draw_img", draw_img)
cv2.waitKey (0)

Upvotes: 1

Related Questions