Home > Back-end >  Mark pixels of a blank image
Mark pixels of a blank image

Time:06-24

I Want to mark the pixels,

Mark=[2, 455, 6, 556, 12, 654, 22, 23, 4,86,.....] in such a way that it will not mark the 1st 2 pixels and then mark next 455 pixels by a color, again for next 6 pixels it will not mark and again mark the next 556 pixels by the same color and so on. The size of the image is 500x500x3. How do I calculate these steps?

Img=np.zeros((500,500,3),dtype=np.uint8)

CodePudding user response:

Your algorithm is actually in your question. By 500x500x3 I guess that you mean your image is 500 (width) on 500 (height) with 3 color channel?

It could be implemented as follows, without any optimizations:

color = (128, 50, 30)
x, y = 0, 0
for (skip, count) in zip([a for i, a in enumerate(Mark) if i % 2 == 0], [a for i, a in enumerate(Mark) if i % 2 != 0]):
    x  = skip
    y  = x // 500  # keep track of the lines, when x > 500,
                       # it means we are on a new line
    x %= 500  # keep the x in bounds

    # colorize `count` pixels in the image
    for i in range(0, count):
        
        Img[x, y, 0] = color[0]
        Img[x, y, 1] = color[1]
        Img[x, y, 2] = color[2]
        x  = 1
        y  = x // 500
        x %= 500  # keep the x in bounds

The zip([a for i, a in enumerate(Mark) if i % 2 == 0], [a for i, a in enumerate(Mark) if i % 2 != 0]) is a just a way to group the pairs (skip, pixel to colorize). It could definitely be improved though, I'm no Python expert.

CodePudding user response:

The easiest way is probably to convert the image to a Numpy array:

import numpy as np
na = np.array(Img)

And then use Numpy ravel() to give you a flattened (1-D) view of the array

flat = np.ravel(na)

You can now see the shape of your flat view:

print(flat.shape)

Then you can do your colouring by iterating over your array of offsets from your question. Then the good news is that, because ravel() gives you a view into your original data all the changes you make to the view will be reflected in your original data.

So, to get back to a PIL Image, all you need is:

RecolouredImg = Image.fromarray(na)

Try it out by just colouring the first ten pixels before worrying about your long list.


If you like working with Python lists (I don't), you can achieve a similar effect by using PIL getdata() to get a flattened list of pixels and then process the list against your requirements and putdata() to put them all back. The effect will be the same, just choose a method that fits how your brain works.

  • Related