3

I'm using GDAL Python API to read a raster into a NumPy array, it will return a array's shape like [bands, rows, cols], if we want to use OpencCV to deal with this array, it will cause some problem, because OpenCV read an image into array' shape like [rows, cols, channels], how can I transfer an array[bands, rows, cols] into an array[rows, cols, channels] and transfer it as fast as I can, I have been using a way to do this job, but it cost a little much time, especially when the data is huge. Downbelow is my way:

import gdal
ds = gdal.open('some raster')
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount
ds_array = ds.ReadAsArray()
gdal2cv2 = np.zeros((rows, cols, bands))
for i in range(len(ds_array)):
    matrix = ds_array[i, :, :]
    gdal2cv2[:, :, i] = matrix

closed as off-topic by user2856, Taras, Fran Raga, LaughU, xunilk Sep 3 at 17:26

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions relating to general IT or with no clear GIS component, are off-topic here but can be researched/asked at Stack Overflow (software development), Super User (computing hardware and software), Database Administrators (relational databases) and other SE sites" – user2856, Taras, Fran Raga, LaughU, xunilk
If this question can be reworded to fit the rules in the help center, please edit the question.

6

numpy.transpose is one way of doing this.

import numpy as np
zyx = np.ones((1, 2, 3))  # 1 band, 2 rows, 3 cols
yxz = np.transpose(zyx, (1,2,0)) 

print(yxz.shape)
# (2, 3, 1)
  • Thank you for your answer, it worked perfectly. But still I need to remind you, it's[rows, cols, channels] that I wanted, so in your code, it is np.transpose(zyx, (1, 2, 0)) rather than np.transpose(zyx, (2, 1, 0)), really appreciate your answer! – Zhou XF Sep 3 at 3:49
  • 1
    @ZhouXF you should accept this answer if it solved your issue. – Marcelo Villa Sep 3 at 14:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.