基于Python+PIL-Speed问题的图像强度归一化

2024-09-27 07:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在业余时间处理一个小问题,包括分析通过显微镜获得的一些图像。它是一个到处都有东西的晶圆,最终我想做一个程序来检测某些材料何时出现。

不管怎样,第一步是将图像的强度标准化,因为镜头不会产生均匀的闪电。目前我使用的图像,没有任何东西,只有基板,作为背景,或参考,图像。我找到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)

代码的第一部分确定了背景图像的红、绿、蓝通道的最大强度(逐像素),但只需要一次。

第二部分获取“真实”图像(上面有东西),并根据背景逐像素地对红、绿、蓝通道进行标准化。这需要一些时间,1280x960图像需要5-10秒,如果需要对多个图像执行此操作,则速度太慢。

如何提高速度?我想将所有图像移动到numpy数组中,但似乎找不到一种快速的方法来处理RGB图像。 我宁愿不离开Python,因为我的C++是相当低的,并且得到一个工作的FORTRAN代码可能要比我在速度方面节省的时间要长:P<


Tags: in图像imageforrangefloatoldim
2条回答

http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.fromimage.html#scipy.misc.fromimage

你可以说

databack = scipy.misc.fromimage(pixback)
rmax = numpy.max(databack[:,:,0])
gmax = numpy.max(databack[:,:,1])
bmax = numpy.max(databack[:,:,2])

它应该比你的图像的所有(r,g,b)三元组循环快得多。 那你就可以了

dataold = scip.misc.fromimage(pixold)
r = dataold[:,:,0] / (pixback[:,:,0] * rmax )
g = dataold[:,:,1] / (pixback[:,:,1] * gmax )
b = dataold[:,:,2] / (pixback[:,:,2] * bmax )

datanew = numpy.array((r,g,b))
imnew = scipy.misc.toimage(datanew)

代码没有经过测试,但是应该可以通过一些小的修改来工作。

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')

相关问题 更多 >

    热门问题