简体   繁体   English

如何将单个像素位置作为 plt.imshow 的参数?

[英]How can I give individual pixel locations as arguments for plt.imshow?

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

image = Image.open(r'C:\Users\oneblackpixel.png')
image2 = np.asarray(image)

fig = plt.figure()
imgplot = plt.imshow([image2[0][0]])
plt.show()

This code prints purple, when actually the image is black in color and is a singular pixel.此代码打印紫色,而实际上图像是黑色的并且是单个像素。

I converted default image pixel values to RGB pallete.我将默认图像像素值转换为 RGB 调色板。 Code is shown below:代码如下所示:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

image = Image.open(r'black_white_image.png')
# image2 = np.asarray(image)
imgRgb = image.convert('RGB')

fig = plt.figure()
plt.imshow(imgRgb)
plt.show()

Here is the code change:这是代码更改:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

image = Image.open(r'C:\Users\oneblackpixel.png')
image2 = np.asarray(image)

fig = plt.figure()

# need a second bracket here:
imgplot = plt.imshow([[image2[0][0]])
plt.show()

Image is read as a 3-d array.图像被读取为 3 维数组。 First and second dimension is the x and y axis of image, third dimension is the color info of pixel.第一维和第二维是图像的 x 和 y 轴,第三维是像素的颜色信息。 In your case, would be [0,0,0,255] if it's black from a .png file.在您的情况下,如果它是 .png 文件中的黑色,则为 [0,0,0,255]。 Value in the array is [R,G,B,Alpha] in order.数组中的值依次为 [R,G,B,Alpha]。 imshow will plot the 4 values from a pixel if you only use 1 bracket.如果您只使用 1 个括号, imshow将从一个像素绘制 4 个值。

did you try reading the image as a matplot image?您是否尝试将图像作为 matplot 图像读取? you do it just like:你这样做就像:

import matplotlib.image as img
image = img.imread("oneblackpixel.png")

it is usually recommended.通常推荐使用。 also, this line:此外,这一行:

imgplot = plt.imshow([image2[0][0]])

turns your image into a 2 dimentional array (which is bad, you will want 3) this will solve that problem:将您的图像转换为 2 维数组(这很糟糕,您需要 3 个)这将解决该问题:

image2 = [[image[0][0]]]

I also did some cleaning, this code shuld work for you我也做了一些清理,这段代码应该对你有用

import matplotlib.pyplot as plt
import matplotlib.image as img
image = img.imread("oneblackpixel.png")

image2 = [[image[0][0]]]

fig = plt.figure()
plt.imshow(image2)
plt.show()

dose that help?剂量有帮助吗?

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

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