11 边缘保留滤波(EPF)
import cv2 as cv
import numpy as np
def bi_demo(image):
dst = cv.bilateralFilter(image, 0, 100, 15)#双边滤波
#参数分别为:输入图像、像素领域的直径、颜色领域的标准差(一般尽可能大)、坐标空间的标准方差(一般尽可能小)
cv.imshow("bi_demo", dst)
def shift_demo(image):
dst = cv.pyrMeanShiftFiltering(image, 10, 50)#均值滤波
#输入参数分别为:原图像、空间窗的半径、色彩窗的半径
cv.imshow("shift_demo", dst)
print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/example.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
bi_demo(src)
shift_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
12 图像直方图(histogram)
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def plot_demo(image):
plt.hist(image.ravel(), 256, [0, 256])#统计频次
plt.show("直方图")
def image_hist(image):
color = ('blue', 'green', 'red')
for i, color in enumerate(color):
hist1 = cv.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist1, color=color)
plt.xlim([0, 256])
plt.show()
print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/test.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
plot_demo(src)
image_hist(src)
cv.waitKey(0)
cv.destroyAllWindows()
13 直方图应用
import cv2 as cv
import numpy as np
def equalHist_demo(image):#直方图均衡化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
dst = cv.equalizeHist(gray)
cv.imshow("equalHist_demo", dst)
def clahe_demo(image):#局部自适应直方图均衡化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
clahe = cv.createCLAHE(clipLimit=5.0, tileGridSize=(8, 8))
dst = clahe.apply(gray)
cv.imshow("clahe_demo", dst)
def create_rgb_hist(image):
h, w, c = image.shape
rgbHist = np.zeros([16*16*16, 1], np.float32)
bsize = 256 / 16
for row in range(h):
for col in range(w):
b = image[row, col, 0]
g = image[row, col, 1]
r = image[row, col, 2]
index = np.int(b/bsize)*16*16 + np.int(g/bsize)*16 + np.int(r/bsize)
rgbHist[np.int(index), 0] = rgbHist[np.int(index), 0] + 1
return rgbHist
def hist_compare(image1, image2):#直方图比较
hist1 = create_rgb_hist(image1)
hist2 = create_rgb_hist(image2)
match1 = cv.compareHist(hist1, hist2, cv.HISTCMP_BHATTACHARYYA)#巴氏距离
match2 = cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL)#相关性
match3 = cv.compareHist(hist1, hist2, cv.HISTCMP_CHISQR)#卡方,越大越不相似
print("巴氏距离: %s, 相关性: %s, 卡方: %s"%(match1, match2, match3))
print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/rise.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
equalHist_demo(src)
clahe_demo(src)
image1 = cv.imread("D:/vcprojects/images/lena.png")
image2 = cv.imread("D:/vcprojects/images/lenanoise.png")
cv.imshow("image1", image1)
cv.imshow("image2", image2)
hist_compare(image1, image2)
cv.waitKey(0)
cv.destroyAllWindows()
--------- Hello Python ---------
巴氏距离: 0.8569864945854435, 相关性: 0.07862638379496767, 卡方: 46585983.69502137
14 直方图反向投影
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def back_projection_demo():#直方图反向投影
sample = cv.imread("D:/vcprojects/images/sample.png")
target = cv.imread("D:/vcprojects/images/target.png")
roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)
# show images
cv.imshow("sample", sample)
cv.imshow("target", target)
roiHist = cv.calcHist([roi_hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])
cv.normalize(roiHist, roiHist, 0, 255, cv.NORM_MINMAX)
dst = cv.calcBackProject([target_hsv], [0, 1], roiHist, [0, 180, 0, 256], 1)
cv.imshow("backProjectionDemo", dst)
def hist2d_demo(image):#2维直方图
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
#hist = cv.calcHist([image], [0, 1], None, [32, 32], [0, 180, 0, 256])
hist = cv.calcHist([image], [0, 1], None, [180, 256], [0, 180, 0, 256])
#cv.imshow("hist2d", hist)
plt.imshow(hist, interpolation='nearest')
plt.title("2D Histogram")
plt.show()
print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png")
#hist2d_demo(src)
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
hist2d_demo(src)
back_projection_demo()
cv.waitKey(0)
cv.destroyAllWindows()
15模板匹配
import cv2 as cv
import numpy as np
def template_demo():
tpl = cv.imread("D:/vcprojects/images/person_head.png")
target = cv.imread("D:/vcprojects/images/pedestrian.png")
cv.imshow("template image", tpl)
cv.imshow("target image", target)
methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]
th, tw = tpl.shape[:2]
for md in methods:
print(md)
result = cv.matchTemplate(target, tpl, md)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
if md == cv.TM_SQDIFF_NORMED:
tl = min_loc
else:
tl = max_loc
br = (tl[0]+tw, tl[1]+th)
cv.rectangle(target, tl, br, (0, 0, 255), 2)
cv.imshow("match-" + np.str(md), target)
#cv.imshow("match-" + np.str(md), result)
print("--------- Python OpenCV Tutorial ---------")
template_demo()
cv.waitKey(0)
cv.destroyAllWindows()
--------- Python OpenCV Tutorial ---------
1
3
5
16图像二值化
import cv2 as cv
import numpy as np
def threshold_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)
print("threshold value %s"%ret)
cv.imshow("threshold_binary", binary)
def local_threshold(image):#自适应阈值二值化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)
cv.imshow("local_threshold_binary", binary)
def custom_threshold(image):#自定义二值化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
h, w = gray.shape[:2]
m = np.reshape(gray, [1, w*h])
mean = m.sum() / (w*h)
print("mean : ", mean)
ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
cv.imshow("custom_threshold_binary", binary)
print("--------- Python OpenCV Tutorial ---------")
#src = cv.imread("D:/vcprojects/images/demo.png")
src = cv.imread("D:/vcprojects/images/case2.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
threshold_demo(src)
local_threshold(src)
custom_threshold(src)
cv.waitKey(0)
cv.destroyAllWindows()
--------- Python OpenCV Tutorial ---------
threshold value 119.0
mean : 148.16271116251838
17 超大图像二值化
import cv2 as cv
import numpy as np
def big_image_binary(image):
print(image.shape)
cw = 256
ch = 256
h, w = image.shape[:2]
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
for row in range(0, h, ch):
for col in range(0, w, cw):
roi = gray[row:row+ch, col:cw+col]
dst=cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127,20)
gray[row:row+ch, col:cw+col]=dst
print(np.std(dst), np.mean(dst))
cv.imwrite("D:/result_binary.png", gray)
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("D:/vcprojects/images/red_text2.png")
big_image_binary(src)
cv.waitKey(0)
cv.destroyAllWindows()
--------- Python OpenCV Tutorial ---------
(7749, 5477, 3)
import cv2 as cv
import numpy as np
def big_image_binary(image):
print(image.shape)
cw = 256
ch = 256
h, w = image.shape[:2]
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
for row in range(0, h, ch):
for col in range(0, w, cw):
roi = gray[row:row+ch, col:cw+col]
print(np.std(roi), np.mean(roi))
dev = np.std(roi)
if dev < 15:
gray[row:row + ch, col:cw + col] = 255
else:
ret, dst = cv.threshold(roi, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
gray[row:row + ch, col:cw + col] = dst
cv.imwrite("D:/vcprojects/result_binary.png", gray)
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("D:/vcprojects/images/red_text2.png")
big_image_binary(src)
cv.waitKey(0)
cv.destroyAllWindows()
--------- Python OpenCV Tutorial ---------
(7749, 5477, 3)
18 图像金字塔
import cv2 as cv
import numpy as np
def pyramid_demo(image):#图像金字塔
level = 3
temp = image.copy()
pyramid_images = []
for i in range(level):
dst = cv.pyrDown(temp)
pyramid_images.append(dst)
cv.imshow("pyramid_down_"+str(i), dst)
temp = dst.copy()#把dst复制给temp
return pyramid_images
def lapalian_demo(image):
pyramid_images = pyramid_demo(image)
level = len(pyramid_images)
for i in range(level-1, -1, -1):
if (i-1) < 0 :
expand = cv.pyrUp(pyramid_images[i], dstsize=image.shape[:2])
lpls = cv.subtract(image, expand)
cv.imshow("lapalian_down_" + str(i), lpls)
else:
expand = cv.pyrUp(pyramid_images[i], dstsize=pyramid_images[i-1].shape[:2])
lpls = cv.subtract(pyramid_images[i-1], expand)
cv.imshow("lapalian_down_"+str(i), lpls)
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("D:/vcprojects/images/lena.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
pyramid_demo(src)
lapalian_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
19 图像梯度
import cv2 as cv
import numpy as np
def lapalian_demo(image):
#dst = cv.Laplacian(image, cv.CV_32F)
#lpls = cv.convertScaleAbs(dst)
kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])
dst = cv.filter2D(image, cv.CV_32F, kernel=kernel)
lpls = cv.convertScaleAbs(dst)
cv.imshow("lapalian_demo", lpls)
def sobel_demo(image):
grad_x = cv.Scharr(image, cv.CV_32F, 1, 0)
grad_y = cv.Scharr(image, cv.CV_32F, 0, 1)
gradx = cv.convertScaleAbs(grad_x)
grady = cv.convertScaleAbs(grad_y)
cv.imshow("gradient-x", gradx)
cv.imshow("gradient-y", grady)
gradxy = cv.addWeighted(gradx, 0.5, grady, 0.5, 0)
cv.imshow("gradient", gradxy)
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("D:/vcprojects/images/shou.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
lapalian_demo(src)
sobel_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()
20 canny边缘提取
import cv2 as cv
import numpy as np
def edge_demo(image):
blurred = cv.GaussianBlur(image, (3, 3), 0)#降噪
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
# X Gradient
xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
# Y Gradient
ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
#edge
#edge_output = cv.Canny(xgrad, ygrad, 50, 150)
edge_output = cv.Canny(gray, 50, 150)
cv.imshow("Canny Edge", edge_output)
dst = cv.bitwise_and(image, image, mask=edge_output)
cv.imshow("Color Edge", dst)
print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("D:/vcprojects/images/test.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
edge_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()