首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python中从非重叠块大小为32×32的图像中提取24维颜色直方图特征向量

如何在python中从非重叠块大小为32×32的图像中提取24维颜色直方图特征向量
EN

Stack Overflow用户
提问于 2018-10-18 00:25:32
回答 1查看 458关注 0票数 -1

我希望读取具有32 x 32个非重叠补丁的图像,并且对于每个补丁,应该用R,G,B值表示,8+8+8 = 24维的特征向量。

EN

回答 1

Stack Overflow用户

发布于 2018-10-18 06:24:52

我假设每个补丁需要三个8-bin直方图,每个颜色通道一个直方图。如果您的图像数据是uint8,那么我们可以通过右移位5位来获得每个像素的适当的二进制索引。实际的组织图可以使用np.bincount +一些温和的技巧来完成,以解决其仅为一维的问题。

这本质上是一行代码。下面的大部分代码都是用来处理非32倍图像维度的。

代码语言:javascript
复制
import numpy as np

def histo24(img):
    h, w, c = img.shape
    assert c == 3
    assert img.dtype == np.uint8
    # pad
    H, W = (h+31)>>5, (w+31)>>5
    patches = np.zeros((H, 32, W, 32, 3), np.uint8)
    patches.reshape(H<<5, W<<5, 3)[:h, :w] = img>>5
    # the next line is the actual histogramming
    histo = np.bincount(
        (patches + np.arange(0, H*W*24, 8).reshape(H, 1, W, 1, 3)).ravel(),
        minlength=H*W*24).reshape(H, W, 24)
    # subtract padded zeros from zero bins at the right and bottom edges
    if h & 31:
        histo[-1, :, ::8] -= (31&-h)<<5
    if w & 31:
        histo[:, -1, ::8] -= (31&-w)<<5
        if h & 31:
            histo[-1, -1, ::8] += (31&-h)*(31&-w)
    return histo

示例:

代码示例:

代码语言:javascript
复制
def visualize(histo):
    h, w, c = histo.shape
    assert c == 24
    vis = np.zeros((h, 32, w, 32, 3), np.uint8)
    idx = np.arange(28)[None, :, None]
    for c in range(3):
        bnds = (histo[..., c<<3:(c+1)<<3].cumsum(axis=-1)*(28/1024)).astype(np.uint8)[..., ::-1]
        for j in range(1, 8):
            view = vis[:, 2:-2, :, 7*c+6:7*c+12, c]
            view[..., 0][(idx >= bnds[:, None, :, j]) &
                         (idx < bnds[:, None, :, j - 1])] = (j<<5)|16
            view[..., 1:] = view[..., :1]
    return vis.reshape(h<<5, w<<5, 3)

from scipy.misc import face
import Image

exmpl = face()
histo = histo24(exmpl)
Image.fromarray(exmpl).show()
#Image.fromarray(exmpl>>5<<5).show()
Image.fromarray(visualize(histo)).show()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52859513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档