2013년 9월 8일 일요일

[openCV, Python] Basic openCV2 usage in python

<Warning>
    This article was written based on my experience.
</Warning>



1. How Read Image in disc?


You can read by using cv2.imread function.

<Caution>
    In python version 2.7, you need writing path '\\', not '\'
</Caution>

<Code>
import cv2
Image = cv2.imread("Path", cv2.CV_LOAD_IMAGE_GRAYSCALE)
</Code>



2. How Show Image in memory?


Need cv2.imshow function

<Caution>
    If you not use cv2.waitKey && ( cv2.destroyWindow || cv2.destroyAllWindows ).
    It make python IDE to restart
</Caution>

<Code>
import cv2

def ShowImage(Image, WinName="TempWinName"):
    cv2.imshow(WinName, Image)
    cv2.waitKey()
    cv2.destroyWindow(WinName)

ShowImage(Image)
</Code>


3. How Get Size of Image?

Because openCV2 use numpy's array.

You can get size by using Image.shape

shape == (Row, Col, nChannel) or (Height, Width, nChannel)

<Caution>
    If Image is 3 channel (like RGB or BGR), shape's length is 3
    If Image is grayscale, shape's length is 2

    So if you access nChannel in grayscale, It raiseIndexError
</Caution>

<Code>

</Code>


4. How Access each pixel in Image?

Just you "[]" :)

<Caution>
    Image[☆Height, ☆Width, nChannel]

    If you access all the pixel by using for(;;),
    It will waste long time

    Must use openCV function as possible as you can.
</Caution>

<Code>

</Code>