如何通过极端点裁剪图像?OPENCV PYTHON

2024-09-28 22:19:52 发布

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

我有这样一个形象: enter image description here

我想剪成这样: enter image description here

我只需要四个点,右上,左上等等。它需要优化和快速,python3opencv。在


Tags: 形象python3opencv
2条回答

我找到了一个有效的方法,非常快。感谢马克·塞切尔和内森。在

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]

你可以做轮廓检测来检测边界框,然后提取感兴趣区域

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

enter image description hereenter image description here

相关问题 更多 >