python opencv 快速均值平滑
import cv2 import numpy as np from datetime import datetime from scipy import signal #二维离散卷积运算 import math def printWithdate(str): time2 = datetime.now() time2a = time2.strftime("%Y-%m-%d %H:%M:%S") print(time2a+' '+str) #python opencv均值平滑 def integral(image): ''' 代码实现积分运算(展示原理)--即任意一个位置的积分等于该位置左上角所有值的和 ''' rows,cols = image.shape #行积分运算 inteImgC=np.zeros((rows,cols),np.float32) for r in range(rows): for c in range(cols): if c == 0: inteImgC[r][c] = image[r][c] else: inteImgC[r][c] = inteImgC[r][c-1]+image[r][c] #列积分运算 inteImg = np.zeros(image.shape,np.float32) for c in range(cols): for r in range(rows): if r==0: inteImg[r][c] = inteImgC[r][c] else: inteImg[r][c] = inteImg[r-1][c]+inteImgC[r][c] #上边盒左边进行补零 inteImg_0 = np.zeros((rows+1,cols+1),np.float32) inteImg_0[1:rows+1,1:cols+1] = inteImg return inteImg_0 def fastMeanblur(img,winSize,borderType = cv2.BORDER_DEFAULT): ''' 代码实现均值平滑,展示原理。 ''' halfH = int((winSize[0]-1)/2) halfW = int((winSize[1]-1)/2) ratio = 1.0/(winSize[0]*winSize[1]) #边界扩充 padImg = cv2.copyMakeBorder(img,halfH,halfH,halfW,halfW,borderType) #图像积分 padImg = integral(padImg) #图像高,宽 rows,cols = img.shape #均值滤波后的结果 meanBlurImg = np.zeros(img.shape,np.float32) r,c = 0,0 for h in range(halfH,halfH+rows,1): for w in range(halfW,halfW+cols,1): meanBlurImg[r][c]=(padImg[h+halfH+1][w+halfW+1] +padImg[h-halfH][w-halfW] -padImg[h+halfH+1][w-halfW] -padImg[h-halfH][w+halfW+1])*ratio c+=1 r+=1 c=0 return meanBlurImg if __name__=="__main__": printWithdate("hello") try: #异常捕捉 ,python 捕捉 imread路径错误 img = cv2.imread(r'dayan.png',cv2.IMREAD_GRAYSCALE) #不会抛出异常,返回none except FileNotFoundError: print('没有找到文件') except IOError as e: print('img read error') except Exception as e: print('未知错误 error') if img is None: print("img is None,程序结束") quit() #程序直接退出不执行后续代码 # cv2.imshow('img',img) # cv2.waitKey(0) # cv2.destroyAllWindows() #图像的积分后,通过定义函数fastMeanBlur来实现均值平滑,其中image是输 #入矩阵,winSize为平滑窗口尺寸,宽、高均为奇数,borderType为边界扩充类型。如果 #在图像的边界进行的处理是补零操作,那么随着窗口的增大,平滑后黑色边界会越来越 #明显,所以在进行均值平滑处理时,比较理想的边界扩充类型是镜像扩充 meanImg = fastMeanblur(img,winSize=(7,7)) # 图像进行灰度级显示 meanImg = np.round(meanImg) meanImg = meanImg.astype(np.uint8) #卷积结果的数据类型是浮点型,假设输入的图像是8位图,进行 #高斯卷积后,需要将结果用命令asty pe(numpy.uint8)进行数据类型转换,从而进行灰 #度级显示,否则用imshow显示时为黑色 cv2.imshow("GaussBlur",meanImg) cv2.waitKey(0) cv2.destroyAllWindows() # new_img = np.zeros(img.shape,np.uint8) # H,W = img.shape # for x in range(H): # for y in range(W): # if img[x][y]<245: # # new_img[x][y] = 0 #0 黑色 # else: # new_img[x][y] = 255 # 亮,白色 # cv2.imwrite('lrc_2.jpg',new_img) # cv2.imshow('a',new_img) # cv2.waitKey(0) # cv2.destroyAllWindows()
欢迎讨论,相互学习。
cdtxw@foxmail.com