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
asked Sep 20, 2017 at 5:33
1
  • 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/… Commented Sep 20, 2017 at 7:22

1 Answer 1

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)
answered Sep 20, 2017 at 7:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.