使用 Opencv 和 Python 从四个角点裁剪图像 [英] Crop image from four corner points using Opencv and Python

查看:134
本文介绍了使用 Opencv 和 Python 从四个角点裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣裁剪多个图像,一组我在数组中的角点.我想裁剪图像并将新的 roi_1、roi_2 等存储在数组/列表中,以便我可以使用 vstack/hstack 方法显示它们.

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.

下面有我的角点.这是我从 cv2.findContour() 函数中获得的,然后过滤掉感兴趣的矩形.

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)]

我的代码

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] 等

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)

这篇关于使用 Opencv 和 Python 从四个角点裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆