Wie teile ich ein Numpy Array (Bild) in Kacheln auf, um es zu durchlaufen? [Duplikat]
Ich habe ein Bild vom Typ Numpy Array, das ich in 9 (3 x 3) gleichmäßige Kacheln aufteilen möchte, über die ich iterieren kann. Wie kann ich das machen?
Hier ist mein bisheriger Code zum Generieren von numpy.ndarray, aber ich habe es nicht geschafft, ihn zu teilen:
Das zu teilende numpy-Bildarray ist th1
import cv2
import numpy as np
# Only for the threshold display
from matplotlib import pyplot as plt
# The Image to be used
image = 'six.png'
# Finding the average greyscale value
image_bgr = cv2.imread(image, cv2.IMREAD_COLOR)
# Calculate the mean of each channel
channels = cv2.mean(image_bgr)
# Type Float
thresh = channels[0]/2
#print (thresh)
# Displaying the threshold value
img = cv2.imread(image,0)
img = cv2.medianBlur(img,5)
# If below then black else white
ret,th1 = cv2.threshold(img,thresh,255,cv2.THRESH_BINARY)
titles = ['Original Image', 'Global Thresholding']
images = [img, th1, ret]
for i in range(2):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
# Shows single image on its' own
plt.imshow(images[1], 'gray')
plt.xticks([]),plt.yticks([])
Hier ist das Bild (six.png):

Antworten
Ich würde eine Liste oder ein zweidimensionales Array erstellen, in dem ich die "Kacheln" des vollständigen Bildes speichern würde. Die Kacheln werden mit dem folgenden Code kopiert:
height, width, dim = img.shape
image_tile = img[0:height/3, 0:width/3]
Es wird eine neue ndarray- Bildkachel erstellt , die den Teil des vollständigen Bildarrays enthält, der sich innerhalb der Koordinaten befindet. In diesem Fall ist es die Kachel oben links.
Das ganze Beispiel mit einer for-Schleife würde ungefähr so aussehen:
image_tile = []
for i in range(0,3):
for j in range(0,3):
image_tile.append(img[i * height/3:(i+1) * height/3, j * width/3:(j+1) * width/3])
Ich hoffe das hilft und viel Glück!
Ich habe eine Lösung gefunden, die von anderswo angepasst wurde und die großartig funktioniert!
img = th1
numrows, numcols = 3, 3
height = int(img.shape[0] / numrows)
width = int(img.shape[1] / numcols)
for row in range(numrows):
for col in range(numcols):
y0 = row * height
y1 = y0 + height
x0 = col * width
x1 = x0 + width
individual = (img[y0:y1, x0:x1])
plt.imshow(individual, 'gray')
plt.xticks([]),plt.yticks([])
plt.show()