OpenCV图像灰度化的六种方法
Opencv4 官方文档 : https://docs.opencv.org/4.2.0/
Opencv4 for Python中文文档点击下载:Opencv4 for Python 中文文档
图像灰度化即是将一幅彩色图像转换为灰度化图像的过程。彩色图像通常包括R、G、B三个分量,分别显示出红绿蓝等各种颜色,灰度化就是使彩色图像的R、G、B三个分量相等的过程。灰度图像中每个像素仅具有一种样本颜色,其灰度是位于黑色与白色之间的多级色彩深度,灰度值大的像素点比较亮,反之比较暗,像素值最大为255(表示白色),像素值最小为0(表示黑色)。比如下图就是灰度化后的图片:
1.环境
Python 3.7 + OpenCV 4.2
2.部分api及其参数解析
- 方法一:读取时灰度化处理
cv.imread(filename, cv.IMREAD_GRAYSCALE)
具体cv.imread及其使用方法参考博客OpenCV图像的加载、显示与保存
- 方法二:调用cvtColor灰度化,其中cvtColor如下:
cv.cvtColor(src, code, dst=None, dstCn=None)
参数 :
- src:input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.输入图像,输入图像:8位无符号,16位无符号(CV_16UC …)或单精度浮点型,其实就是读取输入的原图像。
- code:color space conversion code.色彩空间转换的代码或表示.
- dst:output image of the same size and depth as src.输出图像,大小和深度与原输入图像一致.
- dstCn:number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.目标图像通道数,其值为0时,通道数由输入(src)和输入(code)图像决定.
3.灰度化方法实例及效果
3.1 读取时灰度化处理
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
gray1 = cv.imread(filePath,cv.IMREAD_GRAYSCALE)
cv.imshow("read2gray",gray1)
cv.waitKey(0)
cv.destroyAllWindows()
3.2 调用cvtColor灰度化处理
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
gray2 = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("cvtColor2gray", gray2)
cv.waitKey(0)
cv.destroyAllWindows()
3.3 平均值法:
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
#平均值法
h, w = image.shape[:2]
gray3 = np.zeros((h, w), dtype=np.uint8)
for i in range(h):
for j in range(w):
gray3[i, j] = (int(image[i, j][0]) + int(image[i, j][1]) + int(image[i, j][2])) / 3
cv.imshow("meanGray", gray3)
3.4 最大值法
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
#最大值法
h, w = image.shape[:2]
gray4 = np.zeros((h, w), dtype=np.uint8) # 创建一个h行w列的二维list
for i in range(h):
for j in range(w):
gray4[i, j] = max(image[i, j][0], image[i, j][1], image[i, j][2])
cv.imshow("maxGray",gray4)
3.5 分量法
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
#分量法:
gray6 = cv.imread(filePath, cv.IMREAD_COLOR)
for i in range(gray6.shape[0]):
for j in range(gray6.shape[1]):
gray6[i, j] = gray6[i, j, 0]
cv.imshow("componentGray",gray6)
3.6 加权平均法
def img2Gray(filePath):
image = cv.imread(filePath)
cv.imshow("sourcePic",image)
#加权平均分
h, w = image.shape[:2]
gray5= np.zeros((h, w), dtype=np.uint8)
for i in range(h):
for j in range(w):
# Y = 0.3R + 0.59G + 0.11B
# 通过cv格式打开的图片,像素格式为 BGR
gray5[i, j] = 0.3 * image[i, j][2] + 0.11 * image[i, j][0] + 0.59 * image[i, j][1]
cv.imshow("weightedGray",gray5)
转载请注明转自:https://leejason.blog.csdn.net/article/details/106416128