思路很简单,就是读取图片,获取高宽,创造一个图片的模板,然后依次将三个通道的像素加权融合一下,再保存。
import cv2
import numpy as np
import os
root = "./test"
for file in os.listdir(root):
print(file)
image = cv2.imread(os.path.join(root,file))
#读取图片像素高宽
sp = image.shape
height = sp[0]
width = sp[1]
#创建同样高宽的画布
new = np.zeros((height,width), np.uint8)
#遍历每个像素
#使用加权平均法算得灰度图
for i in range(height):
for j in range(width):
new[i,j] = 0.1 * image[i,j][0] + 0.1 * image[i,j][1] + 0.1 * image[i,j][2]
cv2.namedWindow('Image')
cv2.imshow('Image', new)
new_path = "./test/"+ file.split(".")[0] + "_grey.png"
cv2.imwrite(new_path, new)
cv2.waitKey(0)
cv2.destroyAllWindows()