1

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.

1
  • I would use hough transform to detect rectangles and then filter by orientation and size. I dont think a simple edge detector will work in your case. Commented Feb 1, 2017 at 10:06

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

I will apply your suggestion. Thanks for the heads up
Thanks @Nilay its working. But I did some adjustments for larger book spines, like for example a dictionary. Again, thanks!
I'm facing a similar problem. If you still have the code, can you please share the adjustments you made? (Perhaps as an edit to the original question)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.