I am a programming beginner. I am using images and I want to analyse them with simple codes (for the beginning).
I have images (JPEG files) with black points on a white background. I would like to create a heatmap or a dense map to identify regions where I have a lot of points and where I have few points.
I saw some people are using histogram2d where I have to input x and y coordinates. I know an image is an array and therefore it contains the x,y coordinates of pixels but I dont know how I access them to use the function histogram2d for example. Can someone help me? Since I am beginner I would like to have some explanations and I would be very thankful if someone can be so kind to explain it.
Perhaps there is also another function I could use for this approach. If so, please give me some advice
Thank you in advance for helping me.
I realized that I need to get the black pots first. So I adjusted the code:
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)
When I tried the first part seperatly like above it worked well, I got two arrays with the x and y coordinates! So I putted the two codes together:
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)
And then I got an Error I do not understand.
(Annotation) C:\Users\die5k\Desktop\NeuerOrdner>python combi.py Traceback (most recent call last): File "combi.py", line 31, in getcoordinates(img) File "combi.py", line 13, in getcoordinates xcoords, ycoords = np.where((n[:, :, 0:3] == [0,0,0]).all(2)) IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed
What went wrong?
By the way for this I cutted the original image so that it only contains one black dot for trying the code.
An image example which I have: enter image description here
I would like to have something like they show in this website: https://python-graph-gallery.com/86-avoid-overlapping-in-scatterplot-with-2d-density/