Reputation: 63
I've generated barcode images in PNG format using HuBarcode, and have modified them to add a border of rgb(150, 150, 150)
in hopes of accessing the pixels of that color to change them. I can access the pixel and get confirmation via print
that the color is being changed, but when I open the image file, nothing has changed. The pixels are still rgb(150, 150, 150)
. Here's a code snippet I'm using. I can add more of my code if it will be helpful:
def add_colored_border(self, barcode):
img = Image.open(barcode)
img = img.convert('RGB')
px = img.load()
for x in range(img.size[0]):
for y in range(img.size[1]):
pixel = px[x, y]
if pixel == (150, 150, 150):
pixel = (0, 0, 255)
img.save('testing.png')
Upvotes: 4
Views: 2040
Reputation: 55469
You need to copy the modified pixel value back into the pixel access object. Eg,
if px[x, y] == (150, 150, 150):
px[x, y] = (0, 0, 255)
There's an example in the old PIL docs for Image.load().
If you're modifying a lot of pixels, you may wish to use getdata() and putdata(). Those links are to the docs of the new fork of PIL known as Pillow, but those functions are also available in the old PIL.
pixel = px[x, y]
if pixel == (150, 150, 150):
pixel = (0, 0, 255)
doesn't do what you want because pixel = (0, 0, 255)
creates a new tuple and binds that to the name pixel
, it doesn't modify the tuple in the PixelAccess object at px[x, y]
.
Tuples are immutable, so they can't be modified - if you want to change them you need to replace them with a new tuple. Python does let you modify lists in a way similar to what you were trying, since lists are mutable. To make this work, we need to use a list of lists, we can't use a simple list of integers or strings since Python integers and strings are immutable.
a = [[i] for i in range(5)]
print a
b = a[2]
print b
b[0] = 7
print b
print a
output
[[0], [1], [2], [3], [4]]
[2]
[7]
[[0], [1], [7], [3], [4]]
This works because I'm modifying the contents of b
. But if I do
c = a[3]
c = [11]
print a
output
[[0], [1], [7], [3], [4]]
Now a
is unchanged. The assignment to c
binds a new list to c
, it doesn't touch the a[3]
object that c
was previously bound to.
For more on this important topic please see the excellent illustrated article Facts and myths about Python names and values by SO member Ned Batchelder.
Upvotes: 3