理论

当完全聚焦时,图像最清晰,图像中的高频分量也最多,故可将灰度变化作为聚焦评价的依据,灰度方差法的公式如下:
SMD(灰度方差) - 图1
https://blog.csdn.net/Real_Myth/article/details/50827940

代码

  1. def SMD(img):
  2. '''
  3. :param img:narray 二维灰度图像
  4. :return: float 图像约清晰越大
  5. '''
  6. shape = np.shape(img)
  7. out = 0
  8. for x in range(0, shape[0]-1):
  9. for y in range(1, shape[1]):
  10. out+=math.fabs(int(img[x,y])-int(img[x,y-1]))
  11. out+=math.fabs(int(img[x,y]-int(img[x+1,y])))
  12. return out

https://blog.csdn.net/Greepex/article/details/90183018

4. SMD(灰度方差)函数

当完全聚焦时,图像最清晰,图像中的高频分量也最多,故可将灰度变化作为聚焦评价的依据,灰度方差法的公式如下:
SMD(灰度方差) - 图2

代码:

  1. def SMD(img):
  2. # 图像的预处理
  3. reImg = cv2.resize(img, (800, 900), interpolation=cv2.INTER_CUBIC)
  4. img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY) # 将图片压缩为单通道的灰度图
  5. f=self._imageToMatrix(img2gray)/255.0
  6. x, y = f.shape
  7. D = 0
  8. for i in range(x - 1):
  9. for j in range(y - 1):
  10. D += np.abs(f[i+1,j]-f[i,j])+np.abs(f[i,j]-f[i+1,j])
  11. return D

https://gist.github.com/JuneoXIE/d595028586eec752f4352444fc062c44

  1. def _SMDDetection(self, imgName):
  2. # step 1 图像的预处理
  3. img2gray, reImg = self.preImgOps(imgName)
  4. f=self._imageToMatrix(img2gray)/255.0
  5. x, y = f.shape
  6. score = 0
  7. for i in range(x - 1):
  8. for j in range(y - 1):
  9. score += np.abs(f[i+1,j]-f[i,j])+np.abs(f[i,j]-f[i+1,j])
  10. # strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
  11. score=score/100
  12. newImg = self._drawImgFonts(reImg, str(score))
  13. newDir = self.strDir + "/_SMDDetection_/"
  14. if not os.path.exists(newDir):
  15. os.makedirs(newDir)
  16. newPath = newDir + imgName
  17. cv2.imwrite(newPath, newImg) # 保存图片
  18. cv2.imshow(imgName, newImg)
  19. cv2.waitKey(0)
  20. return score

https://github.com/Leezhen2014/python—/blob/master/BlurDetection.py