Skip to content Skip to sidebar Skip to footer

Unsafe Image Processing In Python Like Lockbits In C#

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

Solution 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 = 3ifdata.mode == 'RGB'else4ifdata.mode == 'RGBA'else1
    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.miscdata= scipy.misc.imread(<filename>)

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

Post a Comment for "Unsafe Image Processing In Python Like Lockbits In C#"