Wednesday 17 September 2014

Load, Display and Save an image

Load, Display and Save an image
This post helps you to load,display and save an image using python and openCV.


Steps:

  1. Load image using cv2.imread().
  2. Display image using cv2.namedWindow() and cv2.imshow().
  3. Save the image using cv2.imwrite().
  4. Wait for keyboard button press using cv2.waitKey().
  5. Destroy all windows using cv2.destroyAllWindows().
cv2.imread(filename[,flags])
Parameters:
  • filename – Name of file to be loaded.
  • flags –
    Flags specifying the color type of a loaded image:
    • CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
    • CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
    • CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one
    • >0 Return a 3-channel color image.
    • =0 Return a grayscale image.
    • <0 Return the loaded image as is (with alpha channel)

cv2.imwrite(filename,img[,params])
Parameters:
  • filename – Name of the file.
  • image – Image to be saved.
  • params –
    Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2,paramValue_2, ... . The following parameters are currently supported:
    • For JPEG, it can be a quality ( CV_IMWRITE_JPEG_QUALITY ) from 0 to 100 (the higher is the better). Default value is 95.
    • For WEBP, it can be a quality ( CV_IMWRITE_WEBP_QUALITY ) from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used.
    • For PNG, it can be the compression level ( CV_IMWRITE_PNG_COMPRESSION ) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
    • For PPM, PGM, or PBM, it can be a binary format flag ( CV_IMWRITE_PXM_BINARY ), 0 or 1. Default value is 1.

cv2.imshow(winname,image)
Parameters:
  • winname – Name of the window
  • image – Image to be shown
cv2.waitKey([delay])
Parameters:
  • delay – Delay in milliseconds. 0 is the special value that means “forever”.The function waitKey waits for a key event infinitely (when delay<=0 ) or for delay milliseconds, when it is positive. 
Example:

----------------------

import cv2

# Load an color image in grayscale
img = cv2.imread('image1.jpg',0)

#Display the image
cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
cv2.imshow('image',img)

#Save the image
cv2.imwrite('result.jpg',img)

cv2.waitKey(0)
cv2.destroyAllWindows()
----------------------

1 comment: