使用opencv python检测轮廓后裁剪图像

时间:2019-07-29 10:51:11

标签: python opencv machine-learning image-processing

我试图在检测到轮廓后裁剪图像,然后使用python,opencv和numpy从图像中提取信息。

检测轮廓成功,但是后来我找不到裁剪的方法。我尝试了一些代码,但没有得到想要的结果:

true

enter image here

数组import numpy as np import cv2 image = cv2.imread('2.jpg') # Read in your image blurred=cv2.blur(image,(23,51))#blur the image gray=cv2.cvtColor(blurred,cv2.COLOR_BGR2GRAY)#gray scale ret,threshold=cv2.threshold(gray , 2 , 255 , cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours,hierachy=cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#detect contours mask = np.zeros_like(image) # Create mask where white is what we want, black otherwise cv2.drawContours(mask, contours, 0, (0 ,0,255),1) out = np.zeros_like(image) # Extract out the object and place into output image out[mask == 255] = image[mask == 255] # Now crop mask=mask.transpose(2,0,1).reshape(-1,mask.shape[1]) (x, y) = np.where(mask == 255) (topx, topy) = (np.min(x), np.min(y)) (bottomx, bottomy) = (np.max(x), np.max(y)) topx=topx topy=topy bottomx=bottomx bottomy=bottomy out = out[topx:bottomx,topy:bottomy] print(out) 为空,这很奇怪,因为当我打印outtopxtopybottomx时,我得到了整数,因此从逻辑上讲裁剪会给我结果。

2 个答案:

答案 0 :(得分:0)

通常,如果检测到轮廓,则可以通过在代码中 var target_ss = "your-spreadsheet-id"; var ss_sheets = SpreadsheetApp.openById(target_ss).getSheets(); for (var i = 0; i < ss_sheets.length; i++){ Logger.log(ss_sheets[i].getDataRange().setWrap(true)); } 之后添加以下几行来裁剪轮廓:

contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

答案 1 :(得分:0)

您可以尝试以下方法:

x, y = [], []

for contour_line in contours:
    for contour in contour_line:
        x.append(contour[0][0])
        y.append(contour[0][1])

x1, x2, y1, y2 = min(x), max(x), min(y), max(y)

cropped = img[y1:y2, x1:x2]

来源:https://stackoverflow.com/questions/41069831/opencv-python-crop-image-using-numpy-array?rq=1#=