Opencv图像中如何进行选区裁剪

2024-09-28 22:22:47 发布

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

告诉我如何在Opencv中剪切选定区域。目前,该区域被高亮显示,我希望所有的东西都被删除。白色背景。在

屏幕截图(https://i.stack.imgur.com/jVcUf.jpg

import cv2
import numpy as np
img = cv2.imread("57.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


th, threshed = cv2.threshold(gray, 100, 255, 
cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)
morphed = cv2.morphologyEx(threshed, cv2.MORPH_OPEN, np.ones((2,2)))

cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, 
cv2.CHAIN_APPROX_SIMPLE[-2]

nh, nw = img.shape[:2]
for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    if h < 0.4 * nh:
        continue
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 255), 1, cv2.LINE_AA)

cv2.imshow("gray", img) 

我所能做的,就是选择所有对象的轮廓,然后删除所有少于正文的内容(你只需要留下9个数字)


Tags: import区域imgnpcv2opencv背景白色
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:47

如果已经检测到矩形,则可以用白色背景填充矩形,为此必须更改矩形参数(-1)

cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)

原始图像 enter image description here

用矩形检测的图像

enter image description here

白色背景的图像

enter image description here

我的代码:

^{pr2}$

相关问题 更多 >