Python 计算距图像中心的像素距离 问题

Python 计算距图像中心的像素距离 问题,python,pandas,numpy,Python,Pandas,Numpy,我有一张图像,n像素宽,m像素高。这两个数字都是偶数。像素是正方形。像素值位于numpy数组中 我需要计算每个像素中心到图像中心的距离。即紧邻中心的像素应具有相关值sqrt(2)/2。如果图像类似于棋盘,则与g6正方形对应的像素应具有关联的距离值,该距离值应为(2.5^2+1.5^2)^0.5=2.91 我的解决方案 我通过以下代码完成了任务: import numpy as np import pandas as pd 距离将为: image=np.zeros([2,4]) # let's

我有一张图像,
n
像素宽,
m
像素高。这两个数字都是偶数。像素是正方形。像素值位于numpy数组中

我需要计算每个像素中心到图像中心的距离。即紧邻中心的像素应具有相关值
sqrt(2)/2
。如果图像类似于棋盘,则与g6正方形对应的像素应具有关联的距离值,该距离值应为(2.5^2+1.5^2)^0.5=2.91


我的解决方案 我通过以下代码完成了任务:

import numpy as np
import pandas as pd
距离将为:

image=np.zeros([2,4]) # let's say this is my image
df = pd.DataFrame(image)

distances = \
pd.DataFrame(
df.apply(
    lambda row: (row.index+0.5-len(df.index)/2)**2,axis=0).to_numpy()+\
df.T.apply(
    lambda row: (row.index+0.5-len(df.columns)/2)**2,axis=0).T.to_numpy())\
    .apply(np.sqrt).to_numpy()
正如所料


问题:
有更好的办法吗?我希望能有一个更短、更面向numpy或更透明的方法。

更透明的方法将首先定义图像的中心,例如

  • 在openCV中将数组作为图像读取:

    array([[1.58113883, 0.70710678, 0.70710678, 1.58113883],
           [1.58113883, 0.70710678, 0.70710678, 1.58113883]])
    
  • 然后,对于numpy/图像阵列中的每个像素,您可以通过计算欧几里德距离来计算numpy阵列中每个像素与上述中心之间的距离:

    D=距离欧几里德((xA,yA),(x_中心,y_中心))


  • PS:您可以简单地使用numpy中的img.shape,但openCV为您提供了许多与距离计算相关的方法。

    除了numpy中的这个简单实现之外,我不知道有什么具体的算法可以做到这一点,即使用(从数组形状创建索引数组)和(计算范数)函数。注:我们还通过索引
    中心[:,无,无]
    中的新维度来使用(由于
    索引
    固有输出形状,因此需要索引)


    对于4000x6000图像,Numpy的方法比我计算机中的原始函数快一个数量级以上。您也可以只计算从中心到一个八分之一的距离,然后方便地将结果复制到剩余的八分之一(利用simmetry),但这可能只适用于大图像imho。

    什么是xA&yA?xA和yA是要计算到中心距离的像素的坐标,因此您将传递numpy数组的每个像素,并计算到上面定义的中心的距离。您能在回答中提供相关代码吗?我想要每个像素的距离。
     img = cv2.imread("inputImage")
     height, width = img.shape
    
     x_center=(width/2)
     y_center=(height/2)
    
    import numpy as np
    import pandas as pd
    
    # Numpy function
    def np_function(image):
        center = np.array([(image.shape[0])/2, (image.shape[1])/2])
        distances = np.linalg.norm(np.indices(image.shape) - center[:,None,None] + 0.5, axis = 0)
    
        return distances
    
    # Pandas function
    def pd_function(image):
        df = pd.DataFrame(image)
        
        distances = \
        pd.DataFrame(
        df.apply(
            lambda row: (row.index+0.5-len(df.index)/2)**2,axis=0).to_numpy()+\
        df.T.apply(
            lambda row: (row.index+0.5-len(df.columns)/2)**2,axis=0).T.to_numpy())\
            .apply(np.sqrt).to_numpy()
            
        return distances