如何缩短此代码以制作灰度图像?

问题描述 投票:0回答:1

我已经编写了代码,将导入的图像更改为灰度图像。我不允许使用现成的功能。形状应为(Y,X,3),numpy数组的dtype为'uint8'。

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

def turn_image_to_grey(image):
# 
    R = np.array(img[:, :, 0])
    G = np.array(img[:, :, 1])
    B = np.array(img[:, :, 2])

    R = R / 3             
    G = G / 3
    B = B / 3

    new_value = (R + G + B) 
# 
    grey = image.copy()   
    for value in range(3):
        grey[:,:,value] = new_value

    return plt.imshow(grey)

turn_image_to_grey(img)

这里,img是我已经导入的图像。我应该能够写出使new_value更短的部分(#标签之间的部分),对吗?通过使用np.average。但是我该怎么办?

image numpy python-3.7 rgb
1个回答
0
投票

假设np.sum是具有以下结构的img,您应该能够沿0轴使用numpy.array

img =  np.array([[[255, 0], [255, 0]], [[255, 0], [255, 0]], [[0, 255], [0,255]]])

这是下面的样子:

new_value = np.sum(img, axis = 0) / 3

使用上面的示例将返回:

>>> new_value
array([[170.,  85.],
   [170.,  85.]])

我希望对image的调用中的image.copy()不是np.array的实例–但如果是,则上一行中的newvalue实际上等于您的代码在以下情况下所做的工作:您生成grey数组。换句话说,您的函数可以简单地用作:

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

def turn_image_to_grey(image):
    grey = np.sum(image, axis = 0) / 3
    return plt.imshow(grey)
© www.soinside.com 2019 - 2024. All rights reserved.