在两幅图像的面片上计算函数的最快方法

2024-10-06 11:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个大小相等的图像,我想计算一个函数,假设f在图像的补丁上,在每个图像位置计算一个数

补丁提取很容易

   patches1 = image.extract_patches_2d(img1,(5,5))
   patches2 = image.extract_patches_2d(img2,(5,5))

现在应用这个函数可以如下所示

   result = numpy.zeros((image1.shape[0], img1.shape[1]))
   for i in range(len(image1.shape[0])):
       for j in range(len(image1.shape[1])):
           result[i,j] = f(patches1[i], patches1[j])

但是这太慢了!!!你知道吗

我想知道什么可能是最好的方法来快速计算它和摆脱循环。你知道吗

谢谢

编辑1:

f的实现是

    def f (patch1, patch2):
        return np.sqrt(patch1^2 + patch2^2)

Tags: 函数in图像imageforlenextractrange
2条回答

我试过这个-任何想要测试他们的代码的人都可以复制我的初始化。基本上,它创建一个单一的标准化图像,并将图像的黑色部分作为补丁a与白色部分作为补丁B进行比较

enter image description here

#!/usr/local/bin/python3

import numpy as np
import math

# Generate a standardised "random" array
shape=(768,1024)                                                                        
np.random.seed(42)                                                                      
img = np.random.randint(0,256,shape,dtype=np.uint8) 

def loopy(patch1,patch2): 
    """Version with loops"""
    h, w = patch1.shape[0], patch1.shape[1] 
    result = np.zeros((h, w), dtype=np.float) 
    for i in range(h): 
        for j in range(w): 
            p1 = float(patch1[i,j]) 
            p2 = float(patch2[i,j]) 
            result[i,j] = math.sqrt(p1*p1+p2*p2) 
    return result 

def me(patch1,patch2): 
    A = patch1.astype(np.float) * patch1.astype(np.float) 
    B = patch2.astype(np.float) * patch2.astype(np.float)  
    return np.sqrt(A + B) 

# Run loopy and me and compare results
l = loopy(img[100:200,100:200],img[400:500,400:500])  
m = me(img[100:200,100:200],img[400:500,400:500])                                                                            
print(np.mean(m-l))

%timeit loopy(img[100:200,100:200],img[400:500,400:500])
# 5.73 ms ± 74.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit me(img[100:200,100:200],img[400:500,400:500])
# 40.2 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

您可以使用多处理使其快速:

from concurrent import futures
import itertools
import numpy as np

patches1 = image.extract_patches_2d(img1,(5,5))
H = image.shape[0]; W = image.shape[1]
results = np.zeros(H*W)
with futures.ProcessPoolExecutor(max_workers=8) as exe:
    procs = {exe.submit(f, patches1[i], patches1[j]): i*W+j for (i,j) in itertools.product(range(H), range(W))}
    for r in futures.as_completed(procs):
        ids = procs[r]
        val = r.result()
        results[ids] = val
results = np.reshape(results,(H,W))

有一种更聪明的方法可以做到这一点:优化f,使其在整个image而不是patches1上工作。这里我只展示一种工程方法。你知道吗

相关问题 更多 >