简体   繁体   中英

Crop image from four corner points using Opencv and Python

I am interested in cropping multiple images a set of corner points that I have in an array. I would like to crop the image and store the new roi_1, roi_2 etc in an array/list so that I can display them using vstack/hstack methods.

I have my corner points below.Which I have obtained from cv2.findContour() function and then filtering out the rectangles of interest.

corner_points=[array([[[ 48, 521]],[[ 51, 560]],[[185, 558]],[[182, 519]]], dtype=int32), array([[[ 48, 376]],[[ 51, 413]],[[185, 411]],[[182, 372]]], dtype=int32), array([[[ 49, 199]],[[ 52, 236]],[[184, 232]],[[178,195]]], dtype=int32)]

My code

import cv2
import numpy as np

y_val=[]
for (x,y) in np.ndenumerate(corner_points):
        y_val.append(y)


new_roi1=roi[y_val[7] : y_val[3], y_val[0]:y_val[4]]  #my roi comes from another cropped image
new_roi2=roi[y_val[15] : y_val[11], y_val[8]:y_val[12]]
new_roi3=roi[y_val[23] : y_val[19], y_val[16]:y_val[20]]

hstack=np.hstack((new_roi3,new_roi2,new_roi1))
cv2.imshow('H Stack',hstack)

cv2.imshow("roi1",new_roi1)
cv2.imshow("roi2",new_roi2)
cv2.imshow("roi3",new_roi3)


The problem is I have to manually calculate the y_val[i] - How can I get it automatically pick out the values I want eg y_val[7]: y_val[3], y_val[0]:y_val[4], y_val[15]: y_val[11], y_val[8]:y_val[12] etc

y_val=[]
new_roi=[]
for (x,y) in np.ndenumerate(corner_points):
        y_val.append(y)
        for i in range(len(y_val)):
                new_roi.append(roi[y_val[i+7]:y_val[i+3],y_val[i]:y_val[i+3]])


I am trying something like this.

index=0
list_roi=[] # has images of all the roi i.e student responses
for contour in contours:
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.03 * peri, True)
    r = cv2.boundingRect(contour)
    if len(contour) >= 4 and cv2.contourArea(contour) > 4000 :
        index += 1
        x, y, w, h = cv2.boundingRect(contour)
        roi = img[y:y+h, x:x+w]
        roi=cv2.resize(roi,(width,height))
        list_roi.append(roi)
        draw_contour = cv2.drawContours(img_copy, [contour], -1, (255, 140, 240), 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM