Skip to content
Ville Tirronen edited this page Dec 11, 2011 · 6 revisions

Loading and Saving Images

The following program demonstrates loading and saving an image:

> module Main where
> import CV.Image
> import CV.Edges

> main = do
>   image <- readFromFile "smallLena.jpg" :: IO (Image GrayScale D32)
>   let result = sobel (1,0) s5 image
>   saveImage "Result.png" result

Let us examine this more closely.

  import CV.Image
  import CV.Edges

The CV.Image module contains a wrapper for OpenCV IplImage type and basic image IO operations. The CV.Filters module is contains various edge enhancing filters and edge detectors. Here, they are used to demonstrate a simple image processing operation.

image <- readFromFile "smallLena.jpg" :: IO (Image GrayScale D32)

The CV image type is parametrized over the color and bit-depth of the image, which allows us to avoid several runtime errors, such as passing color images to functions that only work with grayscale images. Since the readFromFile function can load images with different colorspaces and image depths we must give the resulting image an explicit type declaration.

Here we load the image as a grayscale image with pixels represented as 32-bit floating point numbers. This type is suitable for use with the CV.Edges.sobel function, which has the following type: CV.Edges.sobel :: (Int,Int) -> SobelAperture -> Image GrayScale D32 -> Image GrayScale D32

The resulting image is saved with the function saveImage, which detects the fileformat from the given filename:

>   saveImage "Result.png" result

Unfortunately however, OpenCV will abort if the the filename doesn't contain a suitable extension, or if opencv was compiled without support for the specific image type. This will result in a runtime error.

Finally, this program can now be compiled and executed with

@ ghc --make LoadingSaving.hs
@ ./LoadingSaving

The resulting program will produce the file Result.png, which contains this image:

Edge detector applied to lena-image

Clone this wiki locally