Trying to manipulate images using Python
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 follo开发者_JAVA百科wing 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.
In Python bytes
are immutable. You can't change them, that's why it gives you an error when you try to do item assignment. You could convert your immutable bytes
object into a bytearray
:
image = bytearray(image)
for i in range(1,256):
image[i]=0
精彩评论