替换 Numpy 图像中的像素值

Replace pixel values in a Numpy image

我有一个尺寸为 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()

这是结果:有什么问题!!

,图片分辨率有问题。默认图形大小为 6.4 英寸 x 4.8 英寸,默认分辨率为 100 dpi(至少对于当前版本的 matplotlib 而言)。因此默认图像大小为 640 x 480。该图不仅包括 imshow 图像,还包括刻度线、刻度标签、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')