在 OpenCV Python 中裁剪矩形

rbo*_*o13 1 python opencv image-processing

我有一个像图像 这样

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

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)
Run Code Online (Sandbox Code Playgroud)

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

Nil*_*lay 5

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

 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
Run Code Online (Sandbox Code Playgroud)