python - 如何更改 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()
解决方案
我不确定你想做什么。但是我在 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()
推荐阅读
- postgresql - 从 EAV 结构结果集中选择 JSON 值
- reactjs - 如何知道用户已经在firebase中的另一个浏览器上登录
- python - 如何从数据框列形成元组列表
- amazon-web-services - 如何使用 powershell 从 S3 向 Neptune 实例发送 json 数据?
- javascript - 在 Web 视图中从 LocalStorage 读取数据
- ios - CLLocationManager 使用不准确的坐标更新位置
- laravel-5 - 由于身份验证失败,在 codeception 中登录后无法执行操作 [无法发送令牌]
- rust - 如何将具有特征的 mod 导入 rust?此函数接受 1 个参数,但提供了 0 个参数
- angular - Angular 7 ng-pick-datetime 与 ngModel 错误的语言环境
- java - java.net.UnknownHostException:<
> : 未知错误