【问题标题】:Get a three dimensional array as a parameter and return a three dimensional arrays获取一个三维数组作为参数,返回一个三维数组
【发布时间】:2020-07-08 08:45:00
【问题描述】:

我必须编写一个函数 to_red,它应该将绿色和蓝色分量归零并返回结果。我为 Image(.png) 编写了以下代码,以将绿色和蓝色归零并返回红色并且它起作用了。但是,如标题中所述,输入参数必须是 3-d 数组并返回 3-d 数组。应该如何更改我的以下代码。

import numpy as np

将 matplotlib.pyplot 导入为 plt

from matplotlib.pyplot import imshow

def to_red()

src = plt.imread("C:\src\painting.png")

red_channel = src[:,:,0]

red_img = np.zeros(src.shape)

red_img[:,:,0] = red_channel

plt.imshow(red_img) 

plt.show()

【问题讨论】:

    标签: python arrays matplotlib rgb


    【解决方案1】:

    您可以使用numpy 强大的索引功能

    def to_red(src):
        ret = a.copy() 
        ret[:,:,1:] = 0 
        return ret
    

    【讨论】:

      【解决方案2】:

      你可以这样写你的函数:

      import numpy as np 
      import matplotlib.pyplot as plt 
      from matplotlib.pyplot import imshow
      
      def to_red(src):
          # Check if the input dimension is 3
          if not src.ndim == 3:
              # Raise exception or do something
              print ("Dimension mismatch")
              return 0
      
          red_channel = src[:,:,0]
          red_img = np.zeros(src.shape)
          red_img[:,:,0] = red_channel
      
          return red_img
      

      然后你可以这样称呼它

      source_image = plt.imread("C:\src\painting.png")
      
      red_image = to_red(source_image)
      
      plt.imshow(red_image)    
      plt.show()
      

      我还添加了一行来检查输入是否实际上是 3 维的。

      【讨论】:

      • 感谢您的帮助。 ...:)
      猜你喜欢
      • 2017-10-12
      • 2014-07-16
      • 1970-01-01
      • 2021-02-21
      • 2015-10-21
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多