gpt4 book ai didi

python - 计算距图像中心的像素距离

转载 作者:行者123 更新时间:2023-12-02 18:54:11 24 4
gpt4 key购买 nike

import numpy as np
import pandas as pd

问题

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

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


我的解决方案

我通过以下代码完成了任务:

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()

距离将为:

array([[1.58113883, 0.70710678, 0.70710678, 1.58113883],
[1.58113883, 0.70710678, 0.70710678, 1.58113883]])

正如预期的那样。


问题

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

最佳答案

更透明的方法是首先定义图像的中心,即类似

  1. 在 openCV 中将数组读取为图像:

     img = cv2.imread("inputImage")
    height, width = img.shape

    x_center=(width/2)
    y_center=(height/2)
  2. 然后,对于 numpy/image 数组中的每个像素,您可以通过计算欧氏距离来计算 numpy 数组的每个像素与上述中心之间的距离:

    D = dist.euclidean((xA, yA), (x_center, y_center))

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

关于python - 计算距图像中心的像素距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66412818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com