系列所有代码,复制粘贴即可运行。
希望有能力的朋友还是拿C++运行一下。
本节讨论图像的二值化,局部二值化,膨胀,腐蚀,开运算,闭运算,顶帽,黑帽等
仍然是利用卷积核,来测量或提取输入图像中相应的形状或特征,以便进一步进行图像分析和目标识别,基本操作有(基本都处理二进制图像):
threshold(src, thresh, maxval, type[,dst])
import cv2
import numpy as np
img = cv2.imread('cat.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 阈值 处理后图片
ret, dst = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)
#print(dst)
cv2.imshow('dog', np.hstack((gray, dst)))
cv2.waitKey(0)
cv2.destroyAllWindows()
同一图像上,不同部分具有不同亮度时。根据图像上每一个小区域计算与其对应的阈值,从而能在亮度不同的情况下得到更好的结果
#自适应阈值只返回一个值,即二值化后的图像
##这里的kernel size仍然只是一个数
dst = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,0)
#print(dst)
腐蚀操作也是用卷积核扫描图像,大部分腐蚀操作的卷积核内数字都是1,卷积操作就是相乘再相加
import cv2
import numpy as np
cat = cv2.imread('homework.jpg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
#定义核
kernel = np.ones((5,5), np.uint8)
dst = cv2.erode(img, kernel, iterations=1)
cv2.imshow('cat', np.hstack((img, dst)))
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
cat = cv2.imread('homework.jpg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
#自主获取的卷积核
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
dst = cv2.erode(img, kernel, iterations=1)
cv2.imshow('cat', np.hstack((img, dst)))
cv2.waitKey(0)
cv2.destroyAllWindows()
膨胀是腐蚀的反操作,只要保证卷积核的锚点是非0值,周边值均变为非零值
import cv2
import numpy as np
cat = cv2.imread('homework.jpg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
#定义核
#kernel = np.ones((5,5), np.uint8)
#自主获取的卷积核
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
dst = cv2.dilate(img, kernel, iterations=1)
cv2.imshow('cat', np.hstack((img, dst)))
cv2.waitKey(0)
cv2.destroyAllWindows()
#开运算提供了另一种去噪声的思路
cat = cv2.imread('cat.jpeg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
#腐蚀
#dst = cv2.erode(img, kernel, iterations=2)
#膨胀
#dst = cv2.dilate(img,kernel, iterations=2)
#直接调用opencv提供的开运算
dst = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations=2)
cv2.imshow('img', np.hstack((img, dst)))
cat = cv2.imread('cat.jpeg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
#膨胀
#dst = cv2.dilate(img,kernel, iterations=2)
#腐蚀
#dst = cv2.erode(img, kernel, iterations=2)
#直接调用opencv提供的开运算
dst = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel, iterations=2)
cv2.imshow('img', np.hstack((img, dst)))
import cv2
import numpy as np
cat = cv2.imread('cat.jpeg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
#调节kernel大小获得更清晰的边缘,腐蚀掉的东西
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
dst = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel, iterations=1)
cv2.imshow('img', np.hstack((img, dst)))
cv2.waitKey(0)
cv2.destroyAllWindows()
cat = cv2.imread('cat.jpeg')
img = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)
#调节kernel大小以保留小图形
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (19,19))
dst = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel, iterations=1)
cv2.imshow('img', np.hstack((img, dst)))