我在业余时间处理一个小问题,包括分析通过显微镜获得的一些图像.这是一个带有一些东西的晶圆,最终我想制作一个程序来检测某些材料何时出现.
无论如何,第一步是规范化图像的强度,因为镜头不能提供均匀的闪电.目前,我使用的图像没有任何东西,只有基板,作为背景或参考图像.我找到了RGB的三个(强度)值的最大值.
- from PIL import Image
- from PIL import ImageDraw
- rmax = 0;gmax = 0;bmax = 0;rmin = 300;gmin = 300;bmin = 300
- im_old = Image.open("test_image.png")
- im_back = Image.open("background.png")
- maxx = im_old.size[0] #Import the size of the image
- maxy = im_old.size[1]
- im_new = Image.new("RGB",(maxx,maxy))
- pixback = im_back.load()
- for x in range(maxx):
- for y in range(maxy):
- if pixback[x,y][0] > rmax:
- rmax = pixback[x,y][0]
- if pixback[x,y][1] > gmax:
- gmax = pixback[x,y][1]
- if pixback[x,y][2] > bmax:
- bmax = pixback[x,y][2]
- pixnew = im_new.load()
- pixold = im_old.load()
- for x in range(maxx):
- for y in range(maxy):
- r = float(pixold[x,y][0]) / ( float(pixback[x,y][0])*rmax )
- g = float(pixold[x,y][1]) / ( float(pixback[x,y][1])*gmax )
- b = float(pixold[x,y][2]) / ( float(pixback[x,y][2])*bmax )
- pixnew[x,y] = (r,g,b)
代码的第一部分确定背景图像的逐个像素的RED,GREEN和BLUE通道的最大强度,但只需要进行一次.
第二部分采用“真实”图像(上面有东西),并根据背景逐像素地对RED,GREEN和BLUE通道进行标准化.对于1280×960图像,这需要一些时间,5-10秒,如果我需要对多个图像执行此操作,则速度太慢.
我该怎么做才能提高速度?我想将所有图像移动到numpy数组,但我似乎无法找到一种快速的方法来处理RGB图像.
我宁愿不离开python,因为我的C级别很低,并且获得一个有效的FORTRAN代码可能需要比我在速度方面节省的时间更长:P
解决方法
- import numpy as np
- from PIL import Image
- def normalize(arr):
- """
- Linear normalization
- http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
- """
- arr = arr.astype('float')
- # Do not touch the alpha channel
- for i in range(3):
- minval = arr[...,i].min()
- maxval = arr[...,i].max()
- if minval != maxval:
- arr[...,i] -= minval
- arr[...,i] *= (255.0/(maxval-minval))
- return arr
- def demo_normalize():
- img = Image.open(FILENAME).convert('RGBA')
- arr = np.array(img)
- new_img = Image.fromarray(normalize(arr).astype('uint8'),'RGBA')
- new_img.save('/tmp/normalized.png')