【问题标题】:Sum of the occurence of color(hue) values(0-359) from a set of images一组图像中出现的颜色(色调)值(0-359)的总和
【发布时间】:2019-06-22 12:04:52
【问题描述】:

我有一个装满图像的文件夹,我想找到出现次数最少的色相值。为此,我为所有色调值创建了一个长度为 360 的数组,取出我文件夹中的所有图像,遍历它,对于每个像素,我在数组中的索引处添加 +1,表示色调值。例如,如果我的像素中有色调值 0,我会在我的数组中的索引 0 处添加 +1。 我的问题是:有没有更快或更有效的方法来做到这一点?

这是我的代码:

path = 'path'
sub_path = 'sub_path'
sumHueOcc = np.zeros((360, 1), dtype=np.uint64)

for item in dirs:
    fullpath = os.path.join(path,item)
    pathos = os.path.join(sub_path,item)
    if os.path.isfile(fullpath):
        f, e = os.path.splitext(pathos)
        img = np.array(Image.open(fullpath))
        img = np.float32(img)     
        imgHSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV_FULL) #RGB because numpy RGB

        # want to work with hue only
        h, s, v = cv2.split(imgHSV)

        # the hue values in one large array
        Z = np.array(h, copy=True)
        Z = Z.reshape((-1, 1))

        # convert to np.float32
        Z = np.uint64(Z)

        # count each appearence from hue values
        for z in Z:
            sumHueOcc[z] = sumHueOcc[z] + 1


max = np.argmax(sumHueOcc)
min = np.argmin(sumHueOcc)
print("Minimum 1")
print(min)
sumHueOcc[min] += max
min = np.argmin(sumHueOcc)
print("Minimum 2")
print(min)
sumHueOcc[min] += max
min = np.argmin(sumHueOcc)
print("Minimum 3")
print(min)
sumHueOcc[min] += max
min = np.argmin(sumHueOcc)
print("Minimum 4")
print(min)

【问题讨论】:

  • 仅供参考,在 OpenCV 中,uint8 图像的 H 值在 (0, 180) 中
  • 所以基本上你想要一个histogram 的数据?
  • @Miki 是的,我知道。我不小心复制了 Half Hue 的代码。现在我的代码是正确的。
  • @ThomasKühn 是和否。我已经有一个直方图。这是我的另一个问题。但我想要出现次数最少的值。我可以从直方图中得到吗?

标签: python-3.x image numpy opencv image-processing


【解决方案1】:

我们可以使用np.bincount进行计数。

所以,我们在开头初始化输出数组int64 -

sumHueOcc_out = np.zeros((180, 1), dtype=np.int64) 

然后,在循环内部,我们替换涉及循环的最里面的部分 -

# the hue values in one large array
Z = np.array(h, copy=True)
Z = Z.reshape((-1, 1))

# convert to np.float32
Z = np.uint64(Z)

# count each appearence from hue values
for z in Z:
    sumHueOcc[z] = sumHueOcc[z] + 1

使用bincount 替代 -

sumHueOcc_out.flat += np.bincount(h.astype(np.int64).ravel(),minlength=sumHueOcc.size)

【讨论】:

  • 谢谢!你能告诉我为什么它更好/更快/更有效吗?我现在看不到...是不是因为在我的循环中我通过所有像素而使用 np.bincount 它更有效地通过所有像素?
  • @MartinO 仅仅因为我们使用了矢量化bincount
  • 也许您也可以帮助我解决我的其他问题:stackoverflow.com/questions/54291952/… 我想要一种有效的方法来构建直方图。如果我使用 sumHueOcc_out,它将交换 x 和 y 轴...
  • 抱歉,我的代码一开始就错了。我编辑了它。现在范围是 0-359。
  • 因此,我有一个名为 sumHueOcc_out 的数组,长度为 360,并且在每个索引上都有出现的值。如何打印直方图,其中 x 轴上的范围为 0-360,y 轴上的值来自我的数组?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 2020-08-03
  • 2011-08-14
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多