首页 > 解决方案 > 如何从图像中获取 x,y 坐标以生成热图(python)

问题描述

我是一个编程初学者。我正在使用图像,我想用简单的代码分析它们(一开始)。

我有白色背景上有黑点的图像(JPEG 文件)。我想创建一个热图或密集图来识别我有很多点和我有很少点的区域。

我看到有些人使用 histogram2d 我必须输入 x 和 y 坐标。我知道图像是一个数组,因此它包含像素的 x,y 坐标,但我不知道如何访问它们以使用函数 histogram2d 例如。有人能帮我吗?因为我是初学者,所以我想得到一些解释,如果有人能这么好心地解释一下,我将非常感激。

也许还有另一个函数可以用于这种方法。如果是这样,请给我一些建议

预先感谢您帮助我。

我意识到我需要先拿到黑锅。所以我调整了代码:

import cv2
import numpy as np
import matplotlib.pyplot as plt
import random


#read image
img = cv2.imread("C:\\Users\\die5k\\Desktop\\NeuerOrdner\\eins.jpg")

#make Numpy array from image
n = np.array(img)

#search black pixels
#and gives an array of x and y coordinates of black pixels
#blacks = np.where((n[:, :, 0:3] == [0,0,0]).all(2))

xcoords, ycoords = np.where((n[:, :, 0:3] == [0,0,0]).all(2))

print(xcoords)
print(ycoords)

当我像上面那样单独尝试第一部分时效果很好,我得到了两个带有 x 和 y 坐标的数组!所以我把两个代码放在一起:

import cv2
import numpy as np
import matplotlib.pyplot as plt


def getcoordinates(img):
    #make Numpy array from image
    n = np.array(img)

    #search black pixels
    #and gives an array of x and y coordinates of black pixels
    xcoords, ycoords = np.where((n[:, :, 0:3] == [0,0,0]).all(2))

    print(xcoords)
    print(ycoords)


def getHistogramm(xcoords, ycoords):
    plt.hist2d(xcoords,ycoords,bins=50,cmap=plt.cm.jet)

    plt.title("test")

    plt.savefig("test1", bbox_inches='tight')

    plt.close()


if __name__ == '__main__':
    img = cv2.imread("C:\\Users\\die5k\\Desktop\\NeuerOrdner\\eins.jpg",0)
    getcoordinates(img)
    getHistogramm(xcoords, ycoords)

然后我得到一个我不明白的错误。

(注解)C:\Users\die5k\Desktop\NeuerOrdner>python combi.py Traceback(最近一次调用最后):文件“combi.py”,第31行,在getcoordinates(img)文件“combi.py”,第13行, 在 getcoordinates xcoords, ycoords = np.where((n[:, :, 0:3] == [0,0,0]).all(2)) IndexError: too many indices for array: array is 2-维度,但有 3 个被索引

什么地方出了错?

顺便说一句,我剪切了原始图像,使其仅包含一个用于尝试代码的黑点。

我有一个图像示例: 在此处输入图像描述

我想在这个网站上展示一些类似的东西:https ://python-graph-gallery.com/86-avoid-overlapping-in-scatterplot-with-2d-density/

标签: pythonimageheatmaphistogram2d

解决方案


推荐阅读