2

Trying to manipulate images using Python

 2 years ago
source link: https://www.codesd.com/item/trying-to-manipulate-images-using-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Trying to manipulate images using Python

advertisements

I am trying to learn Python, this is the first code that I have written:

    #!/usr/bin/python
    # Filename: read_image.py

    f=open('1.raw','r+b')
    image=f.read()
    f.close()

    f=open('copy.raw','w+b')
    f.write(image)
    f.close()

    for i in range(1,256):
        image[i]=0

In the first part I am simply reading a '.raw' image as a binary file and making a copy of it. This part works fine on its own and I get a copy of the image after execution of the code. However I wish to manipulate this image, for starters I was trying to blacken the first line of the image, however I get the following error:

Traceback (most recent call last):
  File "C:/Python32/read_image.py", line 15, in <module>
    image[i]=0
TypeError: 'bytes' object does not support item assignment

I tried using 'int' type variables by copying the image into them, however the error persists except instead of 'bytes' object does not support assignment, I get 'int' object does not support assignment. How should I go about solving this problem?

Please note this is a grayscale image, and the pixel values range from 0 to 255, I tried printing the array image on the shell and it showed me values in this range.


If you're really trying to do image processing in Python, try the Python Imaging Library* (PIL) found here: http://www.pythonware.com/products/pil/

[*] Keep in mind that you will have to use Python 2.x as opposed to 3.x if you use this library, unfortunately as is currently the case with a lot of powerful python libraries.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK