Suppose we extract pixels with a specific value from a grayscale image and then highlight these pixels by using a scatter plot on the same image.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
image = cv2.imread('images/wa_state_highway.jpg')
copy_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray_image = cv2.cvtColor(copy_image, cv2.COLOR_RGB2GRAY)
plt.matshow(gray_image, cmap='gray')
# Get the index of elements with value 12
result = np.where(gray_image == 12)
print('Tuple of arrays returned : ', result, sep='\n')
print('List of coordinates where element with value 0 exists in red channel : ')
# zip the 2 arrays to get the exact coordinates
listOfCoordinates = list(zip(result[0], result[1]))
# iterate over the list of coordinates
# for cord in listOfCoordinates:
# print(cord)
x_val = [x[0] for x in listOfCoordinates]
y_val = [x[1] for x in listOfCoordinates]
plt.scatter(x_val, y_val)
plt.show()
I need to match the coordinates of scatter points with the corresponding coordinate on the image.
Solved after @warped comment:
Digital images are accessed by a pair of coordinates (x,y) with the positive x axis pointing to the right and the positive y axis pointing down, so that x specifies the column and y specifies the row , and (0,0) indicates the top-left pixel. Then a pixle pair would be in the form (col, row)
.
On the other hand, an entry of a matrix is written using two indices, say (x,y), where x is the row number and y is the column number. Then a matrix index would be in the form (row, col)
.
So suppose we have a list of tuples returned by np.where
, we need one more step to convert matrix indices to pixle coordinates simply by reversing the elemnets in each tuple.
# Create a 5x5 image using just grayscale, numerical values
tiny_image = np.array([[0, 20, 30, 150, 120],
[200, 200, 250, 70, 3],
[50, 180, 85, 40, 90],
[240, 100, 50, 255, 10],
[30, 0, 75, 190, 220]])
# To show the pixel grid, use matshow
# plt.matshow(tiny_image, cmap='gray')
# Get the index of elements with value zero (black pixles)
result = np.where(tiny_image == 250);
listOfCoordinates = list(zip(result[0], result[1]))
print('Matrix index: ', listOfCoordinates)
print(tiny_image[1,2])
x_val= [x[0] for x in listOfCoordinates]
y_val = [x[1] for x in listOfCoordinates]
# Reverse each tuple in a list of tuples: https://www.geeksforgeeks.org/python-reverse-each-tuple-in-a-list-of-tuples
print('Pixle Coordinates: ', [tup[::-1] for tup in listOfCoordinates])
plt.matshow(tiny_image, cmap='gray')
plt.scatter(y_val, x_val)
plt.show()
# print(len(result))
# print(result[0].shape)
# print(result[1].shape)
# print(tiny_image.shape)
# print(tiny_image.size)
# print(result[0][0:100])
# print(result[1][0:100])
Matrix index: [(1, 2)] 250 Pixle Coordinates: [(2, 1)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.