3

I am working on a program that uses both OpenCV and GDAL to perform different tasks. OpenCV stores its images as numpy arrays. I would like to be able to go directly from this numpy array to a dataset object without having to save the image to the file system and then reopen it again in GDAL. Right now, I have to do this for each image:

import cv2
import numpy as np
from osgeo import gdal

img = cv2.imread("image.png", flags=-1)
# modify the image
cv2.imwrite("output.png", img)
ds = gdal.Open("output.png")
# do stuff with GDAL

The issue is that the cv2.imwrite step is very time consuming, especially since I'm doing it for a lot of images.

My question is this: is there a way to get a dataset from a numpy array directly?

Something like this:

import cv2
import numpy as np
from osgeo import gdal

img = cv2.imread("image.png", flags=-1)
# modify the image
ds = gdal.datasetFromArray(img)
# do stuff with GDAL
Victor Odouard
  • 133
  • 1
  • 5
  • A lot of this depends on what you understand as "do stuff with GDAL". Are you reprojecting the data or something similar? You you can create a GDAL dataset, do your manipulations and in the end write the array into it. See for instance: https://gis.stackexchange.com/questions/37238/writing-numpy-array-to-raster-file – Kersten Sep 20 '17 at 07:22

1 Answers1

6

You could use the gdal_array.OpenArray() function, where ds is a GDAL dataset:

import cv2
import numpy as np
from osgeo import gdal
from osgeo import gdal_array

img = cv2.imread("image.png", flags=-1)
# modify the image
ds = gdal_array.OpenArray(img)
Saleika
  • 1,320
  • 12
  • 18