[英]Crop image from four corner points using Opencv and Python
我有興趣裁剪多個圖像一組我在數組中的角點。 我想裁剪圖像並將新的 roi_1、roi_2 等存儲在數組/列表中,以便我可以使用 vstack/hstack 方法顯示它們。
我在下面有我的角點。我從cv2.findContour()
function 獲得,然后過濾掉感興趣的矩形。
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)]
我的代碼
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)
問題是我必須手動計算 y_val[i] - 我怎樣才能讓它自動挑選出我想要的值,例如 y_val[7]: y_val[3], y_val[0]:y_val[4], y_val[15 ]: y_val[11], y_val[8]:y_val[12] 等
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]])
我正在嘗試這樣的事情。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.