简体   繁体   English

在OpenCV Python中裁剪矩形

[英]Crop rectangle in OpenCV Python

I have an image like this 我有一个像图像这样

and I want to crop each book from the shelf. 我想从书架上剪下每本书。 I started it with this code. 我用这段代码开始了。

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)

I created a bounding box in each of the books from the shelf, but unfortunately this gives me the output . 我在书架上的每本书中创建了一个边界框,但遗憾的是这给了我输出 I want only to draw a bounding box in the side/corner of the books and then crop it from the bounding box. 我只想在书的侧面/角落画一个边界框,然后从边界框中裁剪出来。

I don't think you can explicitly identify only books with this code but one quick improvement you can do in code is to draw contours which have area greater than some value. 我不认为您只能明确识别具有此代码的书籍,但您可以在代码中进行的一项快速改进是绘制面积大于某个值的轮廓。 Following code snippet 以下代码段

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM