[英]scatter plot of pixel values at the same locations in the image
假設我們從灰度圖像中提取具有特定值的像素,然后在同一圖像上使用散點圖 plot 突出顯示這些像素。
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()
我需要將散點的坐標與圖像上的相應坐標相匹配。
在@warped 評論后解決:
數字圖像通過一對坐標 (x,y) 訪問,x 軸正向指向右側,y 軸正向指向下方,因此 x 指定列,y 指定行,而 (0,0) 表示左上角的像素。 然后像素對將采用(col, row)
形式。
另一方面,矩陣的條目使用兩個索引寫入,例如 (x,y),其中 x 是行號,y 是列號。 然后矩陣索引將采用(row, col)
形式。
所以假設我們有一個由np.where
返回的元組列表,我們還需要一個步驟來將矩陣索引轉換為像素坐標,只需通過反轉每個元組中的元素。
# 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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.