python - 如何将图像更改为表示为 NumPy 数组的灰度

标签 python numpy image-processing

前言:

我有一张硬币的图片。这是我插入 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 循环,因为它们很慢。

所以从这张图片开始:

enter image description here

你想要这样的东西:

#!/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')

enter image description here

关于python - 如何将图像更改为表示为 NumPy 数组的灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52232068/

相关文章:

python - 对二进制数据使用 Urllib2.urlopen 失败?

python - 快速创建 2 个大型随机矩阵并将它们相乘

python - 在 NumPy 数组中搜索序列

python - numpy.array 与 img_to_array

python - Pyzbar 无法识别 CODE-128 条形码

python - scikit 管道 python 中的多个分类模型

python - 绘制 3D numpy 数组的第三轴

Python正则表达式nltk网站提取

Python 导入带有多个分隔符的数据

python - 判断图像是亮的还是暗的