前言:
我有一张硬币的图片。这是我插入 python 的硬币的任何通用图像,我想让这枚硬币成为灰度图像。变量 P
表示包含硬币图片的 RGB 值的数组,我相信我可以通过更改 128
下的任何 RGB 值将 RGB 转换为灰度。至 0
同时将任何 RGB 值转为 128
以上至 255
.
错误:
我正在尝试使用 for 循环来转换由 P
生成的数组中的值至 0
, 128
, 和 255
.当我这样做时,我遇到了如下错误:
TypeError: '<' not supported between instances of 'tuple' and 'int' ".
代码:
import numpy as np
import matplotlib.pyplot as plt
P = plt.imread('coin.jpg')
for item in enumerate(P):
if item < 128:
item = 0
elif item > 128:
item = 255
最佳答案
两个问题。首先,您没有转换为灰度。其次,numpy
的全部意义在于矢量化并避免 for
循环,因为它们很慢。
所以从这张图片开始:
你想要这样的东西:
#!/usr/local/bin/python3
import numpy as np
from PIL import Image
# Load coins and convert to greyscale
grey = np.array(Image.open('coins.png').convert('L'))
# Threshold at 128
thresholded=((grey>128)*255).astype(np.uint8)
# Save
Image.fromarray(thresholded).save('result.png')
关于python - 如何将图像更改为表示为 NumPy 数组的灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52232068/