opencv 直线检测 java_在opencv中使用Hough变换检测垂直线

说实话,我不是寻找线条,而是寻找白色的盒子 .

准备

import cv2

import numpy as np

加载图像

img = cv2.imread("digitbox.jpg", 0)

二进制化,以便框和数字都是黑色,其余为白色

_, thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)

cv2.imwrite('digitbox_step1.png', thresh)

zjMfS.png

查找轮廓 . 在此示例图像中,只需查找外部轮廓即可 .

_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

处理轮廓,过滤掉任何面积太小的轮廓 . 找到每个轮廓的凸包,创建轮廓外的所有区域的蒙版 . 存储每个找到的轮廓的边界框,按x坐标排序 .

mask = np.ones_like(img) * 255

boxes = []

for contour in contours:

if cv2.contourArea(contour) > 100:

hull = cv2.convexHull(contour)

cv2.drawContours(mask, [hull], -1, 0, -1)

x,y,w,h = cv2.boundingRect(contour)

boxes.append((x,y,w,h))

boxes = sorted(boxes, key=lambda box: box[0])

cv2.imwrite('digitbox_step2.png', mask)

KXFuv.png

扩大面具(收缩黑色部分),剪掉任何残留的灰色框架 .

mask = cv2.dilate(mask, np.ones((5,5),np.uint8))

cv2.imwrite('digitbox_step3.png', mask)

oJaIO.png

用白色填充所有蒙版像素,以擦除帧 .

img[mask != 0] = 255

cv2.imwrite('digitbox_step4.png', img)

q5utT.png

根据需要处理数字 - 我只是绘制边界框 .

result = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

for n,box in enumerate(boxes):

x,y,w,h = box

cv2.rectangle(result,(x,y),(x+w,y+h),(255,0,0),2)

cv2.putText(result, str(n),(x+5,y+17), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(255,0,0),2,cv2.LINE_AA)

cv2.imwrite('digitbox_step5.png', result)

c7005563d15d5a2cd0ad1f80859a752a.png

整个剧本是一体的:

import cv2

import numpy as np

img = cv2.imread("digitbox.jpg", 0)

_, thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)

_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

mask = np.ones_like(img) * 255

boxes = []

for contour in contours:

if cv2.contourArea(contour) > 100:

hull = cv2.convexHull(contour)

cv2.drawContours(mask, [hull], -1, 0, -1)

x,y,w,h = cv2.boundingRect(contour)

boxes.append((x,y,w,h))

boxes = sorted(boxes, key=lambda box: box[0])

mask = cv2.dilate(mask, np.ones((5,5),np.uint8))

img[mask != 0] = 255

result = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

for n,box in enumerate(boxes):

x,y,w,h = box

cv2.rectangle(result,(x,y),(x+w,y+h),(255,0,0),2)

cv2.putText(result, str(n),(x+5,y+17), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(255,0,0),2,cv2.LINE_AA)

cv2.imwrite('digitbox_result.png', result)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值