从元组列表python numpy中获取颜色



所以我有一个numpy数组,我把它转换成像这样的元组列表

orig_img = cv2.imread("plane.jpg")

def cvimg_to_list(img: numpy.ndarray) -> list:
img_lst = [] 
img_row = img.shape[0] # Width
img_column = img.shape[1] # Height
for x in range(0, img_row): # (Width * Height)
for y in range(0, img_column): 
img_lst.append((img[x,y][0],  #B value
img[x,y][1],  #G value
img[x,y][2])) #R value
return img_lst
orig_list = cvlib.cvimg_to_list(orig_img)
print(orig_list) #hundreds of thousands of values
>>> [(139, 80, 48), (135, 82, 39), ...] 

现在我想写一个函数generator_from_image,它获取一个图像并返回一个函数,该函数给定了一个像素的索引并返回该像素的颜色。

返回的函数应该看起来像一维列表中的图像表示。索引0的返回值是左上角的像素,图像宽度的返回值为右上角,依此类推

以下是我尝试过的:

def generator_from_image(img):

def get_color_from_index(x, y):
color = (x, y) #Need help here...
return color
return get_color_from_index(img)
  • 如果您想要在generator_from_image以像素列表为输入的情况下返回(x,y(处的原始像素,则需要图像的原始图像形状,例如(img_row, img_column, 3)

你可以做:

def generator_from_image(img):

def get_color_from_index(x, y):
color = img[x*img_column + y]
return color
return get_color_from_index

这里所做的是将x跳到原始图像的运行次数img_column的倍,并将y相加以达到平坦索引。

  • 此外,您可以执行以下操作:img.reshape((-1, 3)).tolist()获取列表,img.reshape((-1, 3))获取numpy数组,而不是循环使用img_rowimg_columnappend像素

最新更新