import cv2 from PIL import Image import matplotlib.pyplot as plt import numpy as np from matplotlib import cm def convolution(img1): n,m = img1.shape img_new = [[0 for i in range(m)] for i in range(n)] for i in range(n-3): for j in range(m-3): img2 = img1.copy() a = img2[i:i+3,j:j+3] #定义滑动窗口 w,u=a.shape ave=np.sum(a)/(w*u)#计算窗口总平均灰度值 k=9 value=0 for p in range(w): for q in range(u): if a[p][q]<ave: a[p][q]=0 else: a[p][q]=1 value=value+np.power(2,k-1) #由二进制转化为10进制 k=k-1 img_new[i+1][j+1]=value return img_new
img = cv2.imread(“fish.png”) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #opencv默认通道是BGR,但大多数其他图像处理库使用RGB排序 gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) plt.imshow(img)#原图 plt.show() plt.imshow(gray,cmap=cm.gray)#灰度图 plt.show() n,m = gray.shape print(“n=%d,m=%d”%(n,m)) img_new = convolution(gray) #MCT修正统计变换
卷积结果可视化
plt.imshow(img_new,cmap=cm.gray) plt.show()
结果如下: 原图: 灰度图: MCT变换后的图:
|