我需要编写一些代码,以获得图像中的RGB颜色列表,然后将它们转换为实验室颜色的NumPy数组。我成功地做到了这一点,但我想知道如何才能更有效地做到这一点。
from skimage.color import rgb2lab
from skimage.io import imread
import numpy as np
from PIL import Image # @UnresolvedImport
def get_histogram (img):
#histogram = plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)
w, h = img.size
colours = img.getcolors(w*h) #Returns a list [(pixel_count, (R, G, B))]
num, colours_rgb = zip(*colours)
r,g,b = zip(*colours_rgb)
num_of_colours = len(r)
w2,h2 = 1,num_of_colours
data = np.zeros( (w2,h2,3), dtype=np.uint8)
print(data.shape)
data[0,:,0] = r
data[0,:,1] = g
data[0,:,2] = b
print(data)
colours_lab = rgb2lab(data)
发布于 2014-01-27 08:07:07
get_histogram
没有docstring。这个功能是做什么的?img
参数应该传递什么样的对象?skimage.io.imread
和PIL.Image
,但两者都不使用。print
语句。我假设这些都是调试会话遗留下来的,而您忘记了删除它们。您可能会发现学习使用Python调试器很有用,这将避免将print
语句添加到代码中。num
数组中的颜色计数。)这让我想知道你在用这个函数做什么。numpy.array
函数,则从Python列表创建Numpy数组通常很简单。没有必要乱搞numpy.zeros
和按列分配。因此,我会写以下几点:
import numpy as np
def distinct_colors(img):
"""Return the distinct colors found in img.
img must be an Image object (from the Python Imaging Library).
The result is a Numpy array with three columns containing the
red, green and blue values for each distinct color.
"""
width, height = img.size
colors = [rgb for _, rgb in img.getcolors(width * height)]
return np.array(colors, dtype=np.uint8)
转换到实验室的颜色空间是如此简单,我不认为它需要一个功能。
有一个小困难:skimage.color
函数都需要一个三维或四维数组,因此只支持二维和三维图像。你的一系列不同的颜色是一个一维图像,所以它被拒绝了.但是,您可以很容易地使用numpy.reshape
将其转换为第一个维度为1的二维图像,然后将其传递给rgb2lab
,如下所示:
colors = distinct_colors(img)
rgb2lab(colors.reshape((1, -1, 3)))
或者,如果您希望第二维度为1,请使用.reshape((-1, 1, 3))
。
(我个人认为skimage.color
的行为是荒谬的。为什么它关心维度的数量?在代码中似乎没有任何明显的原因。也许值得提交一份错误报告?)
https://codereview.stackexchange.com/questions/39997
复制相似问题