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– Kersten2017年09月20日 07:22:19 +00:00Commented Sep 20, 2017 at 7:22
1 Answer 1
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)