如何在opencv中裁剪出非矩形、非多边形的ROI?

2024-09-27 21:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想裁剪出图像中非矩形、非多边形的部分,其中包含文字,然后我将使用OCR进行处理

我已经找到了物体的轮廓,看起来像这样: contour

我需要得到尽可能精确的裁剪结果,因此我不能使用近似多边形或矩形的方法

以下是输入图像和代码:

input image

import cv2
import numpy as np
import imutils

shape = cv2.imread("testImg.jpg")
resized = imutils.resize(shape, width=600)
gray = cv2.cvtColor(resized,cv2.COLOR_BGR2GRAY)
th3 = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)[1]

cv2.imshow("th3",th3)

#find contours of thresh
contours, hierarchy = cv2.findContours(th3, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print("Number of Contours found = " + str(len(contours))) 

#a black screen
out = np.zeros_like(resized)
#copy of thresh
copy=th3.copy()

#find largest contour area and draw it
cntArea = []
for c in contours:
    cntArea.append(cv2.contourArea(c))
maxArea = max(cntArea)
maxIndex=cntArea.index(max(cntArea))
maxCnts=contours[maxIndex]
cv2.drawContours(out, maxCnts, -1, (0,255,0), 2)

cv2.imshow("out",out)
cv2.waitKey(0)
cv2.destroyAllWindows

我尝试过清除背景轮廓,但由于我的OCR检测方法,它无法工作(下面的图像无法通过我的OCR代码)

cleared out background


Tags: of方法图像importout多边形cv2轮廓
1条回答
网友
1楼 · 发布于 2024-09-27 21:32:43
  1. 创建所需区域的遮罩,轮廓内的每个像素将获得值1,轮廓外的像素将获得值0。您可以使用cv2.drawContours函数,设置厚度=cv2.FILLED来完成此操作。颜色=(1,1,1)
  2. 使用遮罩与原始图像相乘final_img = mask * original_img

相关问题 更多 >

    热门问题