To install the latest OpenCV 3.1 on Anaconda as of February 2016, get it from the following site.
conda install --channel https://conda.anaconda.org/menpo opencv3
Import and check the version.
In [1]: import cv2
In [2]: print cv2.__version__
3.1.0
Read the image with cv2.imread. At this time, the image is BGR. Please note that if you try to display with matplotlib as it is, the color will be strange.
When you read an image with sckit kimage or scipy, it becomes RGB.
The type of the loaded image is numpy array.
In [5]: I = cv2.imread('Lenna.bmp')
In [6]: I = cv2.imread('lena512color.tiff')
In [7]: type(I)
Out[7]: numpy.ndarray
In [8]: from PIL import Image
In [9]: I = Image.open('Lenna.bmp')
In [10]: type(I)
Out[10]: PIL.BmpImagePlugin.BmpImageFile
In [11]: from skimage import io
In [12]: I = io.imread('Lenna.bmp')
In [13]: type(I)
Out[13]: numpy.ndarray
In [14]: Icv = cv2.imread('Lenna.bmp')
In [15]: print Icv[0,0,:]
[125 137 226]
In [16]: print I[0,0,:]
[226 137 125]
In [17]: from scipy import misc
In [18]: I = misc.imread('Lenna.bmp')
In [19]: type(I)
Out[19]: numpy.ndarray
In [20]: print I[0,0,:]
[226 137 125]
In [21]: from matplotlib import image
In [22]: I = image.imread('Lenna.bmp')
In [23]: type(I)
Out[23]: numpy.ndarray
In [24]: print I[0,0,:]
[226 137 125]
If you want to save the image with opencv, use imwrite.
imwrite(filename, img[, params])
In [26]: cv2.imwrite('output.png', I)
Out[26]: True
However, when saving with OpenCV, the colors must be arranged in the order of BGR in Interleaved format. If you save it as it is, it will be as follows.
Use imshow to display the image.
imshow(winname, mat)
import cv2
I = cv2.imread('./data/SIDBA/Lenna.bmp')
cv2.namedWindow('window')
cv2.imshow('window', I)
cv2.waitKey(0)
cv2.destroyAllWindows()
However, if you do this with interactive ipython, ipython will die.
When doing with ipython, it is good to execute startWindowThread first as shown below.
In [7]: I = cv2.imread('./data/SIDBA/Lenna.bmp')
In [8]: cv2.startWindowThread()
Out[8]: 1
In [9]: cv2.namedWindow('window')
In [10]: cv2.imshow('window', I)
In [11]: cv2.waitKey(0)
Out[11]: 10
In [12]: cv2.destroyAllWindows()
However, if you want to display an image, it is easier to use matplotlib unless you have a specific reason.
In [12]: import matplotlib.pyplot as plt
...: import cv2
...:
...: I = cv2.imread('./data/SIDBA/Lenna.bmp')
...:
...: plt.imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
...: plt.show()
If you read the image with opencv, the image is BGR, so you need to convert it to RGB to display it with matplotlib. In such a case, use cvtColor.
import numpy as np
import cv2
import matplotlib.pyplot as plt
I = cv2.imread('./data/SIDBA/Lenna.bmp')
J = cv2.cvtColor(I, cv2.COLOR_BGR2RGB)
plt.imshow(J)
plt.show()
Recommended Posts