在OpenCV Python中裁剪矩形

时间:2017-02-01 09:32:11

标签: python opencv image-processing

我有一个像这样的图像 this

我想从书架上剪下每本书。我用这段代码开始了。

thresh = cv2.adaptiveThreshold(blur, 255, 1, 1, 11, 2)

cv2.imshow("Gray", gray)
cv2.waitKey(0)

cv2.imshow("Blurred", blur)
cv2.waitKey(0)

# detect edges in the image
edged = cv2.Canny(img, 10, 250)
cv2.imshow("Edged", edged)
cv2.waitKey(0)

# construct and apply a closing kernel to 'close' gaps between 'white'
# pixels
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6))
closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)
cv2.imshow("Closed", closed)
cv2.waitKey(0)

# loop over the contours
for contour in contours:

    # peri = cv2.arcLength(contour, True)
    # approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
    # r = cv2.boundingRect(contour)
    if len(contour) >= 4:
        index += 1
        x, y, w, h = cv2.boundingRect(contour)
        roi = img[y:y+h, x:x+w]
        # cv2.imwrite("a/" + "book - " + str(index) + '.jpg', roi)
        draw_contour = cv2.drawContours(img, [contour], -1, (255, 140, 240), 2)
        total += 1

print contour

cv2.imshow("Drawed Contour", img)
cv2.waitKey(0)

我在书架上的每本书中创建了一个边界框,但不幸的是,这给了我output。我只想在书的侧面/角落画一个边框,然后从边界框中裁剪出来。

1 个答案:

答案 0 :(得分:3)

我认为您不能仅使用此代码明确识别书籍,但您可以在代码中进行的一项快速改进是绘制面积大于某个值的轮廓。以下代码段

 if len(contour) >= 4:
    index += 1
    x, y, w, h = cv2.boundingRect(contour)
    roi = img[y:y+h, x:x+w]
    # cv2.imwrite("a/" + "book - " + str(index) + '.jpg', roi)
    if cv2.contourArea(contour) > 200:
        draw_contour = cv2.drawContours(img, [contour], -1, (255, 140, 240), 2)
        total += 1