使用OpenCV从二进制图像中提取矩形

时间:2019-03-07 12:35:13

标签: python opencv

我正在尝试使用OpenCV和python裁剪图像。我正在关注教程“ https://medium.com/coinmonks/a-box-detection-algorithm-for-any-image-containing-boxes-756c15d7ed26

到目前为止,我的代码:

import os
import cv2
import numpy as np

os.chdir("D:\\RTK\\")


# Read the image
img = cv2.imread('try.jpg', 0)
img1 = cv2.imread('try.jpg')


# Thresholding the image
(thresh, img_bin) = cv2.threshold(img, 128, 255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)

# Invert the image
img_bin = 255-img_bin 
#cv2.imwrite("Image_bin.jpg",img_bin)

# Defining a kernel length
kernel_length = np.array(img).shape[1]//80

# A verticle kernel of (1 X kernel_length), which will detect all the verticle lines from the image.
verticle_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_length))

# A horizontal kernel of (kernel_length X 1), which will help to detect all the horizontal line from the image.
hori_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_length, 1))

# A kernel of (3 X 3) ones.
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))

img_ttt = cv2.dilate(img_bin, kernel, iterations =1)

#cv2.imwrite("Image_bin_dil.jpg",img_ttt)



# Morphological operation to detect vertical lines from an image
img_temp1 = cv2.erode(img_ttt, verticle_kernel, iterations=3)
verticle_lines_img = cv2.dilate(img_temp1, verticle_kernel, iterations=3)
cv2.imwrite("verticle_lines.jpg",verticle_lines_img)

#minLineLength = 100
#maxLineGap = 10
#lines = cv2.HoughLinesP(verticle_lines_img,1,np.pi/180,100,minLineLength,maxLineGap)
#
#for line in lines:
#    for x1,y1,x2,y2 in line:
#        cv2.line(verticle_lines_img,(x1,y1),(x2,y2),(0,0,0),1)
#
#cv2.imwrite('Written_Back_Results.jpg',verticle_lines_img)
# Morphological operation to detect horizontal lines from an image
img_temp2 = cv2.erode(img_ttt, hori_kernel, iterations=3)
horizontal_lines_img = cv2.dilate(img_temp2, hori_kernel, iterations=3)
#cv2.imwrite("horizontal_lines.jpg",horizontal_lines_img)

# Weighting parameters, this will decide the quantity of an image to be added to make a new image.
alpha = 0.5
beta = 1.0 - alpha

# This function helps to add two image with specific weight parameter to get a third image as summation of two image.
img_final_bin = cv2.addWeighted(verticle_lines_img, alpha, horizontal_lines_img, beta, 0.0)
img_final_bin = cv2.erode(~img_final_bin, kernel, iterations=2)
(thresh, img_final_bin) = cv2.threshold(img_final_bin, 128,255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
cv2.imwrite("img_final_bin.jpg",img_final_bin)


# Find contours for image, which will detect all the boxes
im2, contours, hierarchy = cv2.findContours(img_final_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)





def sort_contours(cnts, method="left-to-right"):
    # initialize the reverse flag and sort index
    reverse = False
    i = 0

    # handle if we need to sort in reverse
    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    # handle if we are sorting against the y-coordinate rather than
    # the x-coordinate of the bounding box
    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1

    # construct the list of bounding boxes and sort them from top to
    # bottom
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
        key=lambda b:b[1][i], reverse=reverse))

    # return the list of sorted contours and bounding boxes
    return (cnts, boundingBoxes)



# Sort all the contours by top to bottom.
(contours, boundingBoxes) = sort_contours(contours, method="left-to-right")



idx = 0

for c in contours:

    # Returns the location and width,height for every contour
    x, y, w, h = cv2.boundingRect(c)
    idx += 1
    new_img = img1[y:y+h, x:x+w]

    per_h = (new_img.shape[0]/img1.shape[0])*100.0
    per_w = (new_img.shape[1]/img1.shape[1])*100.0

    if (per_h > 80 and per_w > 80) and (per_h < 100 and per_w < 100):
        cv2.imwrite(str(idx) + '.jpg', new_img)

现在我要提取标记为红色的矩形,但问题是

cv2.findContours is not finding the rectangle marked in red color.

请帮助我从图像2中提取图像1中标记为红色的矩形。

IMAGE 1 

enter image description here

IMAGE 2

enter image description here

0 个答案:

没有答案