首页 > 解决方案 > 是否有任何 python 函数以与 MATLAB 图像完全相同的方式工作到列“im2co”内置函数?

问题描述

我们能否将以下 MATLAB 函数转换为相应的 python 版本:

x1 = im2col(original_image, [block_size block_size], 'distinct');
r1 = col2im(x1, [block_size block_size],[Hight Width], 'distinct');  

我尝试编写以下两个函数,但我的输出与 MATLAB 函数不一样。它无法再次恢复相同的图像。请在下面检查我的代码。

def im2col(mtx, block_size):
    mtx_shape = mtx.shape
    m=mtx.shape[0]
    n=mtx.shape[1]

    mblocks = np.ceil(m/block_size)
    nblocks = np.ceil(n/block_size)

    sx= int(mblocks)
    sy =int(nblocks)

    result = np.empty((block_size * block_size, sx * sy))
    # Moved along the line, so the first holding column (i) does not move down along the row (j)
    for i in range(sy):
        for j in range(sx):
            result[:, i * sx + j] = mtx[j:j + block_size, i:i + block_size].ravel(order='F')
    return result


def col2im(mtx, block_size, image_size):
    p = block_size[0]
    q = block_size[1]

    mblocks = np.ceil(image_size[0]/p)
    nblocks = np.ceil(image_size[1]/q)

    sx= int(mblocks)
    sy= int(nblocks)

    result = np.zeros(image_size)
    weight = np.zeros(image_size)  # Weight record of each cell numbers plus the repeated many times
    col = 0
    # Moved along the line, so the first holding column (i) does not move down along the row (j)
    for i in range(sy):
        for j in range(sx):
            #result[j:j + p, i:i + q] += mtx[:, col].reshape(block_size, order='F')
            result[j:j + p, i:i + q] = result[j:j + p, i:i + q]+ mtx[:, col].reshape(block_size)
            weight[j:j + p, i:i + q] = weight[j:j + p, i:i + q]+  np.ones(block_size)
            col = col + 1
    #return np.divide(result, weight), result
    #return result
    return np.divide(result, weight, out=np.zeros_like(result), where=weight!=0)

要运行它们:

image = cv2.imread('my_image.jpg', cv2.IMREAD_UNCHANGED)
hh = image.shape[0]
wh = image.shape[1]
blk_size =32
x1 = im2col(image, blk_size)  
res1 = col2im(x1, (blk_size, blk_size), (hh, wh))

如果有人提供具有“不同”标准的 MATLAB im2col 的精确 python 版本,我将不胜感激。

但是,此处提供的在线可用函数(链接) 可以返回相同的图像,但它也无法提供精确的 im2col 输出矩阵作为 MATLAB im2col。有维度不同。MATLAB 给出的 x1 维度为 1024x64,而 python 给出的维度为 1024x50625,这是不想要的。

标签: pythonimage-processingsparse-matrixmatrix-multiplication

解决方案


推荐阅读