Ich versuche, jedem Pixel eines Bildes Koordinaten hinzuzufügen. Dazu mache ich Folgendes
import cv2
import numpy as np
img = cv2.imread('images/0001.jpg')
grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
np_grayscale = np.array(grayscale)
# make the array 3d
processed_image = np_grayscale[:,:, np.newaxis]
x = 0
y = 0
for pixel_line in reversed(processed_image):
for pixel in pixel_line:
pixel = np.append(pixel, [x, y])
x += 1
y += 1
print(processed_image)
Dies scheint jedoch nicht zu funktionieren, da ich immer noch das ursprüngliche Array erhalte, das sich im Formular befindet
[[[255]
[255]
[255]
...
[255]
[255]
[255]]
...
...
...
[255]
[255]
[255]]]
Außerdem glaube ich nicht, dass dies der effizienteste Weg ist, weil ich gelesen habe, dass append eine neue Kopie des Arrays erstellt, kann jemand bitte helfen
Lösung des Problems
Sie können ein Netz von Indizes erstellen, indem Sie meshgrid()
und stack()
sie mit dem Originalbild verwenden:
import numpy as np
x = np.asarray([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 255, 0, 0],
[0, 0, 0, 0],
])
indices = np.meshgrid(
np.arange(x.shape[0]),
np.arange(x.shape[1]),
sparse=False
)
x = np.stack((x, *indices)).T
# array([[[ 0, 0, 0],
# [ 0, 0, 1],
# [ 0, 0, 2],
# [ 0, 0, 3]],
# [[ 0, 1, 0],
# [ 0, 1, 1],
# [255, 1, 2],
# [ 0, 1, 3]],
# [[ 0, 2, 0],
# [ 0, 2, 1],
# [ 0, 2, 2],
# [ 0, 2, 3]],
# [[ 0, 3, 0],
# [ 0, 3, 1],
# [ 0, 3, 2],
# [ 0, 3, 3]]])
x[0, 0,:] # 0, 0, 0
x[1, 2,:] # 255, 1, 2
x[-1, -1,:] # 0, 3, 3
Keine Kommentare:
Kommentar veröffentlichen