我想使用 numpy 函数将图像转换为灰度'by hand'



我的函数看起来像这样:

def grey(img):
r = img[:, :, 0]
g = img[:, :, 1]
b = img[:, :, 2]
for row in r:
for column in r:
grey = (r[row, column] + g[row, column] + b[row, column])/3
img[row, column] = grey
return img

我得到的错误信息是ValueError: shape mismatch: value array of shape (3024,) could not be broadcast to indexing result of shape (3024,3)

我是python的新手,尤其是数组,我几乎是在黑暗中。也许RGB值的平均值不会给出一个好的灰色阴影,但这并不重要。

from matplotlib import pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('test.jpg')
R, G, B = img[:,:,0], img[:,:,1],  img[:,:,2]
imgGray = 0.2989 * R + 0.5870 * G + 0.1140 * B
plt.imshow(imgGray, cmap='gray')
plt.show()

这应该会把你的图像变成灰度:)

我要找的是这样的东西:

def grey_scale(img):
"""Converts an image to grayscale"""
avg = np.mean(img, axis=2)  # reads the RGB values and gets the average
grey_img = np.dstack([avg, avg, avg]).astype('uint8')  # stacks the R, G and B channels
return grey_img

相关内容

  • 没有找到相关文章

最新更新