实现
cv2.findContours + OpenCV功能
cv2.threshold(src, thresh, maxval, type, dst=None)
threshold 阈值
功能:当像素值高于阈值时,我们给这个像素赋予一个新值(可能是白色),否则我们给它赋予另一种颜色(也许是黑色)
参数
src 源图像(应为灰度图)
thresh 对像素进行分类的阈值
maxval 当像素高于thresh时被赋予的新的像素值
type OpenCV提供的多种不同的阈值方法
Threshold Binary 即二值化,将大于阈值的灰度值设为最大灰度值,小于阈值的值设为0
Threshold Binary,Inverted 将大于阈值的灰度值设为0,其他值设为最大灰度值。
Truncate 将大于阈值的灰度值设为阈值,小于阈值的值保持不变。
Threshold to Zero 将小于阈值的灰度值设为0,大于阈值的值保持不变。
Threshold to Zero,Inverted 将大于阈值的灰度值设为0,小于阈值的值保持不变。
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("F:\opencv\chapter3\hammer.jpg",cv2.IMREAD_UNCHANGED))
ret,thresh = cv2.threshold(cv2.cvtColor(img.copy(),
cv2.COLOR_BGR2GRAY),127,255,cv2.THRESH_BINARY) #二值化操作
image,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# 计算简单的边界框
x,y,w,h = cv2.boundingRect(c)
# 将轮廓信息转换成(x,y)坐标,并加上矩形的高和宽(w,h)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
# 找到最小矩形区域
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),3)
# 检查边界轮廓为最小闭圆
(x,y),radius = cv2.minEnclosingCircle(c)# 返回一个二元组,圆心坐标组成的元组和圆的半径值
center = (int(x),int(y))
radius = int(radius)
img = cv2.circle(img,center,radius,(0,255,0),2)
cv2.drawContours(img,contours,-1,(255,0,0),1)
cv2.imshow("contours",img)
cv2.waitKey()
cv2.destroyAllWindows()
直线检测
理论基础:Hough变换
HoughLines(image, rho, theta, threshold, lines=None, srn=None, stn=None, min_theta=None, max_theta=None)
HoughLinesP(image, rho, theta, threshold, lines=None, minLineLength=None, maxLineGap=None)
接收一个由Canny边缘检测滤波处理器处理过的单通道二值图像
实际上输入一个经过去噪并只有边缘的图像就行
参数
image 需要处理的图像
rho 线段几何表示 1
theta 线段几何表示 np.pi/180
minLineLength 最小直线长度
maxLineGap 最大线段间隙
import cv2
import numpy as np
img = cv2.imread('F:\opencv\chapter3\lines.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,120)
# 设置最小直线长度和最大线段间隙
minLineLength = 20
maxLineGap = 5
lines = cv2.HoughLinesP(edges,1,np.pi/180,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow("edges",edges)
cv2.imshow("lines",img)
cv2.waitKey()
cv2.destroyAllWindows()
HoughCircles(image, method, dp, minDist, circles=None, param1=None, param2=None, minRadius=None, maxRadius=None)
Hough 变换方式,目前只支持CV2.HOUGH_GRADIENT
详细参数见关于霍夫找圆算法cvHoughCircles的参数
import cv2
import numpy as np
planets = cv2.imread('F:\opencv\chapter3\planet_glow.jpg')
gray_img = cv2.cvtColor(planets,cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,
param1=100,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),2)
cv2.circle(planets,(i[0],i[1]),2,(0,0,255),3)
cv2.imwrite("planets_circles.jpg",planets)
cv2.imshow("HoughCircles",planets)
cv2.waitKey()
cv2.destroyAllWindows()