使用OpenCV从图像中裁剪框-轮廓(Python)

时间:2019-04-18 09:41:04

标签: python python-3.x opencv opencv-contour

我正在使用OpenCV轮廓功能从图像中裁剪框,每个框包含一个手写数字,如果该数字是开箱即用的,则无法使用OpenCV轮廓裁剪图像,如图所示。

enter image description here

这是我尝试过的有效代码...

    self.image = cv2.imread("1.jpg")
    self.res = cv2.imread("1.jpg")
    self.store_path = "cropped/" 

    #define kernal value
    kernel = np.ones((2,2),np.uint8)

    #grayscale
    gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)

    ret, threshold = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
    threshold = cv2.bitwise_not(threshold)       
    dilate = cv2.dilate(threshold,kernel,iterations = 1)

    ret, threshold = cv2.threshold(dilate,127,255,cv2.THRESH_BINARY)
    dilate = cv2.dilate(threshold,kernel,iterations = 1)

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

    test_contours = []
    test_count = 0

    for i in range(1,len(contours)):
        approx = cv2.approxPolyDP(contours[i],cv2.arcLength(contours[i],True)*0.02,True)
        if(abs(cv2.contourArea(contours[i]))<100 or not(cv2.isContourConvex(approx))):
            continue

        if(len(approx) > 0):
            vtc = len(approx)
            cos = []
            for j in range(2,vtc+1):
                cos.append(self.angle(approx[j%vtc],approx[j-2],approx[j-1]))
            cos.sort()
            self.mincos = cos[0]
            self.maxcos = cos[-1]


            x,y,w,h = cv2.boundingRect(contours[i])
            roi = self.image[y:y+h, x:x+w]

            #remove small 
            row, col, channels = roi.shape
            diff = abs(row - col)
            size = roi.size
            if diff < 4 or diff > 50 or size < 5000 or size > 25000:
                continue
            test_count = test_count + 1
            cv2.imwrite(self.store_path + "Answers/" + str(i)+"_"+str(diff)+"_"+str(roi.size)+".jpg", roi) 
            rect = cv2.minAreaRect(contours[i])
            box = cv2.boxPoints(rect)
            box = np.int0(box)
            cv2.drawContours(self.res,[box],0,(0,255,0),2)
            test_contours.append(contours[i])

    print(upload_sheet+"_"+str(self.page_type)+"_"+str(test_count))
    # remove the contours from the image and show the resulting images
    cv2.imwrite(self.store_path + 'res.jpg', self.res)    

#END

0 个答案:

没有答案