简体   繁体   English

如何将图像的像素值复制到另一个 python 变量以使 python 变量将图像保存在 opencv

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

I have created a black image using np.zeros:我使用 np.zeros 创建了一个黑色图像:

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

面具

Now I want to edit this variable named mask turn it into an image I like.现在我想编辑这个名为 mask 的变量,把它变成我喜欢的图像。 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:但这并不起作用,因为 output 是白色图像:

白色图像

If I only use a single value like this.如果我只使用这样的单个值。 It gives me an blue image:它给了我一个蓝色的图像:

蓝色图像

But I didn't use 255, it shouldn't give me a full dark blue image like 255 pixel value:但我没有使用 255,它不应该给我像 255 像素值这样的完整深蓝色图像:

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.但是我正在处理的事情是 r,g,b 3 种颜色的值,二维 arrays,我需要将它们转换为图像。 So I can't just copy paste.所以我不能只是复制粘贴。

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.因此,它默认使用 float 作为其数据类型,然后颜色的范围将在 0-1 之间。 As you are passing value greater than 1, it takes it as the full intensity of that color.当您传递大于 1 的值时,它会将其作为该颜色的全部强度。 Hence, the complete white and blue color images are appearing.因此,出现了完整的白色和蓝色图像。

And also, if you want to copy an image, use this:此外,如果您想复制图像,请使用以下命令:

mask = image.copy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM