一、图像阈值
ret, dst = cv2.threshold(src, thresh, maxval, type)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/31 14:03
# @Author : King110108
# @File : threshold_filter.py
# @Description:
# @IDE : PyCharm
import cv2 #opencv读取的格式是BGR
import matplotlib.pyplot as plt #Matplotlib是RGB
import numpy as np
#显示一张图片,第一个参数是窗口名字,第二个参数是要显示的图片
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#灰度处理
img=cv2.imread('jay1.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
print(img_gray.shape)
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
二、图像平滑处理
图片平滑处理即对图片滤波降噪的过程。
均值滤波--简单的平均卷积操作
blur = cv2.blur(img, (3, 3))
cv2.imshow('blur', blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
方框滤波--基本和均值一样,可以选择归一化,False越界会产生高亮图
boxFilter= cv2.boxFilter(img,-1,(3,3), normalize=True)
cv2.imshow('boxFilter', boxFilter)
cv2.waitKey(0)
cv2.destroyAllWindows()
高斯滤波--高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
aussianBlur = cv2.GaussianBlur(img, (5, 5), 1)
cv2.imshow('aussianBlur ', aussianBlur )
cv2.waitKey(0)
cv2.destroyAllWindows()
中值滤波--相当于用中值代替
medianBlur= cv2.medianBlur(img, 5) # 中值滤波
cv2.imshow('medianBlur', medianBlur)
cv2.waitKey(0)
cv2.destroyAllWindows()