首页 > 解决方案 > 替换 Numpy 图像中的像素值

问题描述

我有一个尺寸为 720*1280 的零图像,我有一个像素坐标列表要更改:

x = [623, 623, 583, 526, 571, 669, 686, 697, 600, 594, 606, 657, 657, 657, 617, 646, 611, 657, 674, 571, 693, 688, 698, 700, 686, 687, 687, 693, 690, 686, 694]

y = [231, 281, 270, 270, 202, 287, 366, 428, 422, 517, 608, 422, 518, 608, 208, 214, 208, 231, 653, 652, 436, 441, 457, 457, 453, 461, 467, 469, 475, 477, 467] 

这是散点图:

yy= [720 -x for x in y]
plt.scatter(x, yy, s = 25, c = "r")
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(0, 1280)
plt.ylim(0, 720)
plt.show()

在此处输入图像描述

这是通过将像素值设置为 255 来生成二进制图像的代码

image_zeros = np.zeros((720, 1280), dtype=np.uint8)
    for i ,j in zip (x, y):
            image_zeros[i, j] = 255

    plt.imshow(image_zeros, cmap='gray')
    plt.show()

结果如下:有什么问题!!

在此处输入图像描述

标签: pythonnumpymatplotlibimshow

解决方案


正如Goyo 指出的那样,图像的分辨率是问题所在。默认图形大小为 6.4 英寸 x 4.8 英寸,默认分辨率为 100 dpi(至少对于当前版本的 matplotlib)。所以默认的图片尺寸是640 x 480。图中不仅包括imshow图片,还包括tickmarks、ticklabels以及x和y轴以及一个白色边框。因此,默认情况下,imshow 图像可用的像素甚至少于 640 x 480 像素。

image_zeros有形状(720、1280)。该数组太大,无法在 640 x 480 像素的图像中完全渲染。

因此,要使用 imshow 生成白点,请设置 figsize 和 dpi 以使 imshow 图像可用的像素数大于 (1280, 720):

import numpy as np
import matplotlib.pyplot as plt

x = np.array([623, 623, 583, 526, 571, 669, 686, 697, 600, 594, 606, 657, 657, 657, 617, 646, 611, 657, 674, 571, 693, 688, 698, 700, 686, 687, 687, 693, 690, 686, 694])
y = np.array([231, 281, 270, 270, 202, 287, 366, 428, 422, 517, 608, 422, 518, 608, 208, 214, 208, 231, 653, 652, 436, 441, 457, 457, 453, 461, 467, 469, 475, 477, 467])

image_zeros = np.zeros((720, 1280), dtype=np.uint8)
image_zeros[y, x] = 255

fig, ax = plt.subplots(figsize=(26, 16), dpi=100)
ax.imshow(image_zeros, cmap='gray', origin='lower')
fig.savefig('/tmp/out.png')

这是显示一些白点的特写镜头:

在此处输入图像描述

为了使白点更容易看到,您可能希望使用 scatter 而不是 imshow:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([623, 623, 583, 526, 571, 669, 686, 697, 600, 594, 606, 657, 657, 657, 617, 646, 611, 657, 674, 571, 693, 688, 698, 700, 686, 687, 687, 693, 690, 686, 694])
y = np.array([231, 281, 270, 270, 202, 287, 366, 428, 422, 517, 608, 422, 518, 608, 208, 214, 208, 231, 653, 652, 436, 441, 457, 457, 453, 461, 467, 469, 475, 477, 467])
yy = 720 - y

fig, ax = plt.subplots()

ax.patch.set_facecolor('black')
ax.scatter(x, yy, s=25, c='white')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlim(0, 1280)
ax.set_ylim(0, 720)
fig.savefig('/tmp/out-scatter.png')

在此处输入图像描述


推荐阅读