理论
当完全聚焦时,图像最清晰,图像中的高频分量也最多,故可将灰度变化作为聚焦评价的依据,灰度方差法的公式如下:
https://blog.csdn.net/Real_Myth/article/details/50827940
代码
def SMD(img):
'''
:param img:narray 二维灰度图像
:return: float 图像约清晰越大
'''
shape = np.shape(img)
out = 0
for x in range(0, shape[0]-1):
for y in range(1, shape[1]):
out+=math.fabs(int(img[x,y])-int(img[x,y-1]))
out+=math.fabs(int(img[x,y]-int(img[x+1,y])))
return out
https://blog.csdn.net/Greepex/article/details/90183018
4. SMD(灰度方差)函数
当完全聚焦时,图像最清晰,图像中的高频分量也最多,故可将灰度变化作为聚焦评价的依据,灰度方差法的公式如下:
代码:
def SMD(img):
# 图像的预处理
reImg = cv2.resize(img, (800, 900), interpolation=cv2.INTER_CUBIC)
img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY) # 将图片压缩为单通道的灰度图
f=self._imageToMatrix(img2gray)/255.0
x, y = f.shape
D = 0
for i in range(x - 1):
for j in range(y - 1):
D += np.abs(f[i+1,j]-f[i,j])+np.abs(f[i,j]-f[i+1,j])
return D
https://gist.github.com/JuneoXIE/d595028586eec752f4352444fc062c44
def _SMDDetection(self, imgName):
# step 1 图像的预处理
img2gray, reImg = self.preImgOps(imgName)
f=self._imageToMatrix(img2gray)/255.0
x, y = f.shape
score = 0
for i in range(x - 1):
for j in range(y - 1):
score += np.abs(f[i+1,j]-f[i,j])+np.abs(f[i,j]-f[i+1,j])
# strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
score=score/100
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_SMDDetection_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
return score
https://github.com/Leezhen2014/python—/blob/master/BlurDetection.py