Unsafe Image Processing in Python like LockBits in C#

别说谁变了你拦得住时间么 提交于 2019-12-11 06:09:54

问题


Is it possible to do Unsafe Image Processing in Python?

As with C# I encountered a hard wall with my pixel processing in Python as getPixel method from Image is simply running too slow.

Is it possible to get a direct access to the image in memory like LockBits in c# does? It will make my program run much faster.

Thanks,

Mark


回答1:


There is nothing "unsafe" about this.

Once you understand how Python works, it becomes patent that calling a method to retrieve information on each pixel is going to be slow.

First of all, although you give no information on it, I assume you are using "Pillow" - the Python Image Library (PIL) which is the most well known library for image manipulation using Python. As it is a third party package, nothing obliges you to use that. (PIL does have a getpixel method on images, but not a getPixel one)

One straightforward way to have all data in a manipulable way is to create a bytearray object of the image data - given an image in a img variable you can do:

data = bytearray(img.tobytes())  

And that is it, you have linear access to all data on your image. To get to an specific Pixel in there, you need to get the image width , heigth and bytes-per-pixel. The later one is not a direct Image attribute in PIL, so you have to compute it given the Image's mode. The most common image types are RGB, RGBA and L.

So, if you want to write out a rectangle at "x, y, width, size" at an image, you can do this:

def rectangle(img, x,y, width, height):
    data = bytearray(img.tobytes())
    blank_data = (255,) * witdh * bpp
    bpp = 3 if data.mode == 'RGB' else 4 if data.mode == 'RGBA' else 1
    stride = img.width * bpp
    for i in range(y, y + height):
         data[i * stride + x * bpp: i * stride + (x + width) * bpp)] = blank_data
    return Image.frombytes(img.mode, (img.width, img.height), bytes(data))

That is not much used, but for simple manipulation. People needing to apply filters and other more complicated algorithms in images with Python usually access the image using numpy - python high-performance data manipulation package, wich is tightly coupled with a lot of other packages that have things specific for images - usually installed as scipy.

So, to have the image as an ndarray, which already does all of the above coordinate -> bytes conversion for you, you can use:

 import scipy.misc
 data = scipy.misc.imread(<filename>)

(Check the docs at https://docs.scipy.org/doc/scipy/reference/)



来源:https://stackoverflow.com/questions/41158375/unsafe-image-processing-in-python-like-lockbits-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!