python - 是否有任何 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,这是不想要的。
解决方案
推荐阅读
- mysql - 无法通过主机名从同一网络中的 Spring Boot 容器访问 mysql 容器
- macos - AirDrop 在 macOS 中禁用检测和设置
- php - PHP 回调 URL 不包括 ?a=complete
- hive - 当我创建一个新提要时,我遇到了这样的问题 保存提要重复键 ProcessGroupDTO:b20b995a-0165-1000-0479-b059731bba5b 时出错
- java - Spring Boot 手动内容协商
- angular - RxJS:根据先前的值来恢复对象,然后将这些先前的值与恢复的对象连接并发出
- python - Python线程不会更改函数内的全局变量
- json - 在 Vertica 中解析 JSON 有效负载
- c# - 允许在临时表上插入身份会产生错误
- c++11 - 进程切换是否会影响 arm9 处理器中的 std::atomic 比较和交换?