0

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
  • 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: gis.stackexchange.com/questions/37238/… – Kersten Sep 20 '17 at 7:22
2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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