答案 0 :(得分:1)
您可以执行轮廓检测以检测边界框,然后提取ROI
import cv2
image = cv2.imread('1.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
ROI = original[y:y+h, x:x+w].copy()
cv2.rectangle(original, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.imshow('ROI', ROI)
cv2.imwrite('ROI.png', ROI)
cv2.waitKey()
答案 1 :(得分:0)
我很快找到了一种有效的方法。感谢Mark Setchell和Nathancy。
colsums = np.sum(img, axis=0)
linessum = np.sum(img, axis=1)
colsums2 = np.nonzero(0-colsums)
linessum2 = np.nonzero(0-linessum)
xx=linessum2[0][0]
yy=linessum2[0][linessum2[0].shape[0]-1]
ww=colsums2[0][0]
hh=colsums2[0][colsums2[0].shape[0]-1]
if xx > 4 :
xx = xx-5
else :
xx = 0
if ww > 4 :
ww = ww-5
else :
ww = 0
if hh < img.shape[1] -6:
hh=hh+5
else :
hh=img.shape[1]-1
if yy < img.shape[0] -6:
yy=yy+5
else :
yy=img.shape[0]-1
imgcrop = img[xx:yy, ww:hh]