霍夫直线检测
霍夫变换直线检测(Line Detection)原理及示例
这位大佬用的是c++版本,但并不影响食用。
然后把自己写的python代码传上来吧。
使用图片:
1.cv.HoughLines()
# coding=UTF-8
import cv2 as cv
import numpy as np
def line_dection(image):
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,50,150,apertureSize=3)
lines = cv.HoughLines(edges,1,np.pi/180,200)
for line in lines:
rho,theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0+1000*(-b))
y1 = int(y0+1000*a)
x2 = int(x0-1000*(-b))
y2 = int(y0-1000*a)
cv.line(image,(x1,y1),(x2,y2),(0,0,255),2)
cv.imshow("line_dection",image)
scr = cv.imread("D:/academic/picture/opencv_data/ela_modified.jpg")
cv.imshow("input image",scr)
line_dection(scr)
cv.waitKey(0)
cv.destroyAllWindows()
效果:
2.cv.HoughLinesP()
# coding=UTF-8
import cv2 as cv
import numpy as np
def line_dection(image):
gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,50,150,apertureSize=3)
lines = cv.HoughLinesP(edges,1,np.pi/180,100,minLineLength=100,maxLineGap=20)
for line in lines:
x1,y1,x2,y2 = line[0]
cv.line(image,(x1,y1),(x2,y2),(0,0,255),2)
cv.imshow("line_dection",image)
scr = cv.imread("D:/academic/picture/opencv_data/ela_modified.jpg")
cv.imshow("input image",scr)
line_dection(scr)
cv.waitKey(0)
cv.destroyAllWindows()
效果:
霍夫圆
看看大佬写的:OpenCv–霍夫圆检测
使用图片:
# coding=UTF-8
import cv2 as cv
import numpy as np
def detect_circle_demo(image):
dst = cv.pyrMeanShiftFiltering(image,10,100)
cimage = cv.cvtColor(dst,cv.COLOR_BGR2GRAY)
circles = cv.HoughCircles(cimage,cv.HOUGH_GRADIENT,1,20,param1=70,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv.circle(image,(i[0],i[1]),i[2],(0,255,255),2)
cv.circle(image,(i[0],i[1]),2,(255,0,0),2)
cv.imshow("circles",image)
scr = cv.imread("D:/academic/picture/opencv_data/stuff.jpg")
cv.imshow("input image",scr)
detect_circle_demo(scr)
cv.waitKey(0)
cv.destroyAllWindows()
效果: