python - 替换 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()
结果如下:有什么问题!!
解决方案
正如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')
推荐阅读
- xml - 从 Spring XML Config 文件中的不同子项目加载 sql 脚本
- pagination - 分页小部件:从编辑或显示返回列表视图时始终位于第 1 页
- push-notification - Amazon Pinpoint 未向较新型号的机器人发送推送通知
- reactjs - 尝试访问本地 json 文件时,您需要启用 javascript 以运行此应用程序响应响应
- shell - Base16 和 Neovim。如何在 linux VT 和 X 终端中使用一致的颜色?
- node.js - 在 wordpress docker 映像上安装 nodejs - 节点:未找到
- python - 将混合输入转换为十六进制
- angularjs - 显示/隐藏和重置 angularjs
- marklogic - Marklogic XDMP-ARGTYPE: (err:XPTY0004) arg0 不是 xs:anyAtomicType 类型?
- python - 在 keras 中添加到(预训练/非训练)神经网络的中间层后训练 softmax 层