【问题标题】:Crop rectangle in OpenCV Python在 OpenCV Python 中裁剪矩形
【发布时间】:2017-02-01 19:59:09
【问题描述】:

我有一个像 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。我只想在书籍的侧面/角落绘制一个边界框,然后从边界框中裁剪它。

【问题讨论】:

  • 我会使用霍夫变换来检测矩形,然后按方向和大小进行过滤。我认为简单的边缘检测器不适用于您的情况。

标签: python opencv image-processing


【解决方案1】:

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

 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

【讨论】:

  • 我会采纳你的建议。感谢您的提醒
  • 感谢@Nilay 的工作。但我对较大的书脊做了一些调整,例如字典。再次感谢!
猜你喜欢
  • 2014-02-03
  • 1970-01-01
  • 2016-09-07
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 2013-02-26
相关资源
最近更新 更多