如何在Opencv图像上剪切选择

时间:2019-06-01 11:20:44

标签: python opencv

告诉我如何在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位数字)

1 个答案:

答案 0 :(得分:0)

如果已经检测到矩形,则可以用白色背景填充矩形,为此必须更改矩形参数(-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

我的代码:

import cv2
import numpy as np

img = cv2.imread("numeros_romanos.jpg")
img = cv2.resize(img, (1024, 800), interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

th, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

im2, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, 
cv2.CHAIN_APPROX_SIMPLE)

for cnt in cnts:
    x,y,w,h = bbox = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 255), -1, cv2.LINE_AA)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()