【问题标题】:Pyplot imshow function displays only axis instead of imagePyplot imshow 函数只显示轴而不是图像
【发布时间】:2021-05-05 13:18:27
【问题描述】:

我创建了一个 python 函数来将图像颜色的每个像素转换为它的原色。它获取每个像素的 rgb 值的最大值,并创建一个只有该颜色的新列表。例如,如果一个像素的 rgb 值为 (250, 100, 23),它会创建一个值为 (256, 0, 0) 的新列表,因为 250 是最大值,并将其附加到一个 numpy 数组。结果如下:https://i.stack.imgur.com/o5Tbc.png,代码如下:

import matplotlib.pyplot as plt
import numpy as np
import skimage.data as data

def draw(list, img):
  #the problem is in this function
  arr = np.array(list)
  arr.reshape(np.shape(img))
  plt.imshow(arr)
  plt.show()
  
def convert(image):
  global x
  #I made x global because I wanted to see if the function worked and it worked
  x = []
  for i in image:
    for o in i:
      if(max(o) == o[0]):
        x.append([255, 0, 0])
      elif max(o) == o[1]:
        x.append([0, 255, 0])
      elif max(o) == o[2]:
        x.append([0, 0, 255])
  draw(x, image)

convert(data.rocket())
#data.rocket() is an image that is a numpy array of shape 427, 640, 3
#data.rocket() is a perfect array that works with the function  

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    问题出在一行:

    arr.reshape(np.shape(img))
    

    方法“.reshpe”不能“就地”工作,但它会返回一个新的重组指针指向数组。对象 arr 不会改变其形状。如果您不想将代码更改太多,请改为:

    arr = arr.reshape(np.shape(img))
    

    但与其将其设为列表并将像素附加到其中,我认为这样做会更好:

    import numpy as np
    
    image = np.random.randint(0, 255, (2, 2, 3))
    maxs = np.argmax(image, axis = 2)
    x = np.zeros_like(image)
    indices = np.indices(image.shape[:-1])
    x[indices[0].flatten(), indices[1].flatten(), maxs.flatten()] = 255
    

    输出:

    image = 
    [[[ 92  34 149]
      [110 171   0]]
    
     [[104  84 189]
      [121 211 177]]]
    x = 
    [[[  0   0 255]
      [  0 255   0]]
     [[  0   0 255]
      [  0 255   0]]]
    

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 2021-06-08
      • 2021-03-13
      • 2020-11-25
      • 2017-11-30
      相关资源
      最近更新 更多