how to copy pixel values of an image to another python variable to make that python variable hold the image in opencv

1.7k Views Asked by At

I have created a black image using np.zeros:

mask = np.zeros((800, 500, 3))

mask

Now I want to edit this variable named mask turn it into an image I like. I know I can access pixel value like this:

for i in range(0,800):
 for j in range(0,500):
    mask[i,j]=[110,23,245]

but this isn't working all I get as an output is an white image:

white image

If I only use a single value like this. It gives me an blue image:

blue image

But I didn't use 255, it shouldn't give me a full dark blue image like 255 pixel value:

for i in range(0,800):
    for j in range(0,500):
        mask[i,j]=[110,0,0]

I know I can copy image like this:

mask=image

but the thing which I am working on I have values of r,g,b colours in 3, two dimensional arrays, I need to convert them into an image. So I can't just copy paste.

1

There are 1 best solutions below

4
On BEST ANSWER

First of all, specify the data type also while creating a black image:

mask = np.zeros((800, 500, 3), dtype=np.uint8)

Then, to color the complete image to another color, you can use slicing methods instead of iterating over all pixels, it will be fast.

Like this:

mask[:, :] = (110,23,245)

The problem in your case is arising because you have not specified the data type while creating the mask image. Thus, it by default uses float as its data type, and then the range of color will be between 0-1. As you are passing value greater than 1, it takes it as the full intensity of that color. Hence, the complete white and blue color images are appearing.

And also, if you want to copy an image, use this:

mask = image.copy()