使用Python PIL对图像进行强度归一化 – 速度问题

前端之家收集整理的这篇文章主要介绍了使用Python PIL对图像进行强度归一化 – 速度问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在业余时间处理一个小问题,包括分析通过显微镜获得的一些图像.这是一个带有一些东西的晶圆,最终我想制作一个程序来检测某些材料何时出现.

无论如何,第一步是规范化图像的强度,因为镜头不能提供均匀的闪电.目前,我使用的图像没有任何东西,只有基板,作为背景或参考图像.我找到了RGB的三个(强度)值的最大值.

  1. from PIL import Image
  2. from PIL import ImageDraw
  3.  
  4. rmax = 0;gmax = 0;bmax = 0;rmin = 300;gmin = 300;bmin = 300
  5.  
  6. im_old = Image.open("test_image.png")
  7. im_back = Image.open("background.png")
  8.  
  9. maxx = im_old.size[0] #Import the size of the image
  10. maxy = im_old.size[1]
  11. im_new = Image.new("RGB",(maxx,maxy))
  12.  
  13.  
  14. pixback = im_back.load()
  15. for x in range(maxx):
  16. for y in range(maxy):
  17. if pixback[x,y][0] > rmax:
  18. rmax = pixback[x,y][0]
  19. if pixback[x,y][1] > gmax:
  20. gmax = pixback[x,y][1]
  21. if pixback[x,y][2] > bmax:
  22. bmax = pixback[x,y][2]
  23.  
  24.  
  25. pixnew = im_new.load()
  26. pixold = im_old.load()
  27. for x in range(maxx):
  28. for y in range(maxy):
  29. r = float(pixold[x,y][0]) / ( float(pixback[x,y][0])*rmax )
  30. g = float(pixold[x,y][1]) / ( float(pixback[x,y][1])*gmax )
  31. b = float(pixold[x,y][2]) / ( float(pixback[x,y][2])*bmax )
  32. pixnew[x,y] = (r,g,b)

代码的第一部分确定背景图像的逐个像素的RED,GREEN和BLUE通道的最大强度,但只需要进行一次.

第二部分采用“真实”图像(上面有东西),并根据背景逐像素地对RED,GREEN和BLUE通道进行标准化.对于1280×960图像,这需要一些时间,5-10秒,如果我需要对多个图像执行此操作,则速度太慢.

我该怎么做才能提高速度?我想将所有图像移动到numpy数组,但我似乎无法找到一种快速方法来处理RGB图像.
我宁愿不离开python,因为我的C级别很低,并且获得一个有效的FORTRAN代码可能需要比我在速度方面节省的时间更长:P

解决方法

  1. import numpy as np
  2. from PIL import Image
  3.  
  4. def normalize(arr):
  5. """
  6. Linear normalization
  7. http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
  8. """
  9. arr = arr.astype('float')
  10. # Do not touch the alpha channel
  11. for i in range(3):
  12. minval = arr[...,i].min()
  13. maxval = arr[...,i].max()
  14. if minval != maxval:
  15. arr[...,i] -= minval
  16. arr[...,i] *= (255.0/(maxval-minval))
  17. return arr
  18.  
  19. def demo_normalize():
  20. img = Image.open(FILENAME).convert('RGBA')
  21. arr = np.array(img)
  22. new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')
  23. new_img.save('/tmp/normalized.png')

猜你在找的Python相关文章