首页 > 解决方案 > 如何更改 cv2.boundingRect 的值

问题描述

有没有办法改变 cv2.boundingRect 的值

在此处输入图像描述

我想进行调整,以便获得准确的 cv2.drawContours 在此处输入图像描述

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box

x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()

标签: pythonopencv

解决方案


我不确定你想做什么。但是我在 Python/OpenCV 中看到了两种不同的方法来解决这个问题。

1)只要增加 w

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find bounding box    
x,y,w,h = cv2.boundingRect(thresh)
w = w + 9
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()


在此处输入图像描述

2)扩大你的阈值图像

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# apply morphology dilate
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, kernel)

# Find bounding box   
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)

cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()


在此处输入图像描述


推荐阅读