python复杂背景下直线检测
1.图片变化
下面这是原始图片:
经过一系列图像处理后,生成的图像如下图所示:
附上python代码:
import cv2
import numpy as np
from skimage import morphology
# 读取彩色图像
img=cv2.imread("E://image//640.png",flags=1)
cv2.imshow("ori",img)
# 获取图像的宽和高
array=img.shape
width=array[0]
height=array[1]
print(type(array))
print(width)
print(height)
# 裁剪图像
cutImg=img[0:height-40,0:width].copy()
cv2.imshow("cut",cutImg)
# 图像进行灰度化
img1=cv2.cvtColor(cutImg,cv2.COLOR_BGR2GRAY)
cv2.imshow("gray",img1)
# 使用中值滤波去除椒盐噪声
blur = cv2.medianBlur(img1,3)
cv2.imshow('blur',blur)
# 取反
blurNot=cv2.bitwise_not(blur)
cv2.imshow('blurNot',blurNot)
# 创建和blurNot相同大小的黑色图像
temp=np.zeros(blurNot.shape,np.uint8)
# temp1=np.zeros_like(blurNot)
# 上述两种写法都可以
cv2.imshow('temp',temp)
# 第一次霍夫直线检测
lines = cv2.HoughLinesP(blurNot, 1, np.pi/180, 10, minLineLength=0, maxLineGap=50)
print(type(lines))
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(temp, (x1, y1), (x2, y2), (255, 255, 255), 2)
cv2.imshow('HoughLine1',temp)
# 对上述图像做细化处理
temp[temp==255] = 1
skeleton = morphology.skeletonize(temp)
thin = skeleton.astype(np.uint8)*255
cv2.imshow("thin",thin)
lines = cv2.HoughLinesP(thin, 1, np.pi / 180, 20, minLineLength=50, maxLineGap=30)
print(len(lines))
# 第二次霍夫直线检测
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(cutImg, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow("houghLine2",cutImg)
cv2.waitKey(0)
文章转自公众号:OpenCV与AI深度学习。