一、滤波
高通滤波器HPF:根据像素与邻近像素的亮度差值来提升该像素的亮度
低通滤波器LPF:在像素与周围像素的亮度差值小于一个特定值时,平滑该像素亮度,去噪和模糊化
import cv2
import numpy as np
from scipy import ndimage
kernel_3x3 = np.array([[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]])
kernel_5x5 = np.array([[-1, -1, -1, -1, -1],
[-1, 1, 2, 1, -1],
[-1, 2, 4, 2, -1],
[-1, 1, 2, 1, -1],
[-1, -1, -1, -1, -1]])
img = cv2.imread("statue_small.jpg", 0)
k3 = ndimage.convolve(img, kernel_3x3)
k5 = ndimage.convolve(img, kernel_5x5)
blurred = cv2.GaussianBlur(img, (17,17), 0)#应用低通滤波器后,与原始图像计算差值
g_hpf = img - blurred#效果最好
cv2.imshow("3x3", k3)
cv2.imshow("5x5", k5)
cv2.imshow("g_hpf", g_hpf)
cv2.waitKey()
cv2.destroyAllWindows()
二、边缘检测:Laplacian(),Sobel(),Scharr()
进行边缘检测之前先进行模糊处理:blur(),medianBlur(),GaussianBlur()
# -*- coding: UTF-8 -*-
import cv2
import numpy
import utils
def strokeEdges(src, dst, blurKsize = 7, edgeKsize = 5):
if blurKsize >= 3 :
blurredSrc = cv2.medianBlur(src, blurKsize)#模糊处理medianBlur()
graySrc = cv2.cvtColor(blurredSrc, cv2.COLOR_BGR2GRAY)
else:
graySrc = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
cv2.Laplacian(graySrc, cv2.CV_8U, graySrc, ksize = edgeKsize)#边缘检测:Laplacian()
normalizedInverseAlpha = (1.0 / 255) * (255 - graySrc)#归一化像素0-1范围
channels = cv2.split(src)#split bgr to b,g,r
for channel in channels:
channel[:] = channel * normalizedInverseAlpha#使边缘变黑
cv2.merge(channels, dst)
#用定制内核做卷积cv2.filter2D()
class VConvolutionFilter(object):
"""A filter that applies a convoltion to V (or all of BGR)"""
def __init__(self, kernel):
self._kernel = kernel
def apply(self, src, dst):
"""Apply the filter with a BGR or gray source/destination."""
cv2.filter2D(src, -1, self._kernel, dst)
class SharpenFilter(VConvolutionFilter):
"""An sharpen filter with a 1-pixel radius."""
def __init__(self):
kernel = numpy.array([[-1, -1, -1], #锐化滤波器 权重和为1
[-1, 9, -1],
[-1, -1, -1]])
VConvolutionFilter.__init__(self, kernel)
class FindEdgesFilter(VConvolutionFilter):
"""An edge-finding filter with a 1-pixel radius"""
def __init__(self):
kernel = numpy.array([[-1, -1, -1], #边缘检测滤波器 权重和为0
[-1, 8, -1],
[-1, -1, -1]])
VConvolutionFilter.__init__(self, kernel)
class BlurFilter(VConvolutionFilter):
"""A blur filter with a 2-pixel radius."""
def __init__(self):
kernel = numpy.array([[0.04, 0.04, 0.04, 0.04, 0.04], #模糊滤波器 权重和为1 且临近权重全为正
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04],
[0.04, 0.04, 0.04, 0.04, 0.04]])
VConvolutionFilter.__init__(self, kernel)
class EmbossFilter(VConvolutionFilter):#不对称的核,模糊和锐化作用,产生脊状或浮雕效果
"""An emboss filter with a 1-pixel radius"""
def __init__(self):
kernel = numpy.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
VConvolutionFilter.__init__(self, kernel)
Canny边缘检测:cv2.Canny(img,200,300)
5个步骤,高斯滤波器去噪,计算梯度,在边缘使用非最大抑制(NMS),在检测到的边缘使用双阈值去除假阳性,
分析所有的边缘及其之间的连接以保留真正的边缘并消除不明显的边缘
三、轮廓检测:
cv2.findContours
cv2.drawContours
cv2.contourArea(contours[i])计算轮廓面积
cv2.arcLength(cnt,True)计算轮廓的周长 True轮廓是否闭合
import cv2
import numpy as np
img = np.zeros((200,200), dtype=np.uint8)
img[50:150, 50:150] = 255
ret, thresh = cv2.threshold(img.copy(), 127, 255, 0)#大于127的置为255 0=cv2.THRESH_BINARY
image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
img = cv2.drawContours(color.copy(), contours, -1, (0,255,0), 2)#-1 所有轮廓,0第0个轮廓
#2 宽 -1填充模式
cv2.imshow("contours", img)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread("images/hammer.jpg", cv2.IMREAD_UNCHANGED)
img = cv2.pyrDown(img)#高斯金字塔 下采样 缩小过程 长宽为原1/2。pyrUp()
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
#cv2.RETR_EXTERNAL得到最外面轮廓 cv2.RETR_TREE得到轮廓的整体层次结构
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# find bounding box coordinates
x,y,w,h = cv2.boundingRect(c)#点集矩形边界
cv2.rectangle(img, (x,y), (x+w, y+h), (200, 200, 20), 2)
# find minimum area
rect = cv2.minAreaRect(c)#最小包围矩形区域
# calculate coordinates of the minimum area rectangle
box = cv2.boxPoints(rect)#矩形区域顶点坐标 float型
# normalize coordinates to integers
box = np.int0(box)
# draw contours
cv2.drawContours(img, [box], 0, (0,0, 255), 3)#第二参数为轮廓的数组
# calculate center and radius of minimum enclosing circle
(x,y),radius = cv2.minEnclosingCircle(c)#最小闭圆 圆心 半径
# cast to integers
center = (int(x),int(y))
radius = int(radius)
# draw the circle
img = cv2.circle(img,center,radius,(255,0,0),2)#画圆 cv2.line画线
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)#最外轮廓
cv2.imshow("contours", img)
cv2.waitKey()
cv2.destroyAllWindows()
五、轮廓检测其他应用:凸轮廓 Douglas-Peucker算法(近似轮廓)
hull = cv2.convexHull(cnt)#凸轮廓 凸包
approx = cv2.approxPolyDP(cnt,epsilon,True)#Douglas-Peucker算法(近似轮廓)
第一个参数 轮廓
第二个参数 e值 近似多边形周长与源轮廓周长差值 越小近似多边形与源轮廓越接近
第三个参数 布尔值 是否闭合
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("images/hammer.jpg", cv2.IMREAD_UNCHANGED))
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
black = cv2.cvtColor(np.zeros((img.shape[1], img.shape[0]), dtype=np.uint8), cv2.COLOR_GRAY2BGR)
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
epsilon = 0.01 * cv2.arcLength(cnt,True)#轮廓的周长 True轮廓是否闭合
approx = cv2.approxPolyDP(cnt,epsilon,True)#近似轮廓
hull = cv2.convexHull(cnt)#凸轮廓 凸包
cv2.drawContours(black, [cnt], -1, (0, 255, 0), 2)
cv2.drawContours(black, [approx], -1, (255, 0, 0), 2)
cv2.drawContours(black, [hull], -1, (0, 0, 255), 2)
cv2.imshow("hull", black)
cv2.waitKey()
cv2.destroyAllWindows()
概率Hough变换 HoughLinesP 计算代价小执行快
lines = cv2.HoughLinesP(edges,1,np.pi/180,20,minLineLength,maxLineGap)
第一个参数: 需要处理的图像
第二三个参数: 线段的几何表示rho和theta 一般取1和np.pi/180
第四个参数: 阈值 低于阈值直线被忽略
第五六个参数: 最小直线长度和最大线段间隙
import cv2
import numpy as np
img = cv2.imread('images/lines.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,120)
minLineLength = 50
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,20,minLineLength,maxLineGap)
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow("edges", edges)
cv2.imshow("lines", img)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.HoughCircles(image, method, dp, minDist, param1, param2, minRadius, maxRadius)
minDist圆心最小距离
minRadius, maxRadius圆最小最大半径
import cv2
import numpy as np
planets = cv2.imread('images/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,:]:
# draw the outer circle
cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(planets,(i[0],i[1]),2,(0,0,255),3)
cv2.imwrite("planets_circles.jpg", planets)
cv2.imshow("HoughCirlces", planets)
cv2.waitKey()
cv2.destroyAllWindows()