0% found this document useful (0 votes)
36 views

Opencv Python Readthedocs Io en Latest

This document provides a summary of OpenCV Python documentation. It discusses how to read and display images, work with video from cameras and files, and draw basic shapes like lines, circles, rectangles, and text onto images using OpenCV functions. Code samples are provided to demonstrate reading, displaying, writing images, reading video from cameras and files, and drawing basic shapes. The document contains 6 chapters that cover goals, functions, and code samples for working with images, video, and basic drawing in OpenCV Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Opencv Python Readthedocs Io en Latest

This document provides a summary of OpenCV Python documentation. It discusses how to read and display images, work with video from cameras and files, and draw basic shapes like lines, circles, rectangles, and text onto images using OpenCV functions. Code samples are provided to demonstrate reading, displaying, writing images, reading video from cameras and files, and drawing basic shapes. The document contains 6 chapters that cover goals, functions, and code samples for working with images, video, and basic drawing in OpenCV Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

OpenCV Python Documentation

Release 0.1

gramman

June 16, 2016


Contents

1 3

2 9

3 13

4 Mouse 17

5 Trackbar 19

6 Indices and tables 21

i
ii
OpenCV Python Documentation, Release 0.1

OpenCV-Python Tutorial .
Contents:

Contents 1
OpenCV Python Documentation, Release 0.1

2 Contents
CHAPTER 1

1.1 Goal
• ,, .
• cv2.imread(), cv2.imshow(), cv2.imwrite() .

1.2

openCV import.:
>>> import cv2

cv2.imread() . /.
>>> img = cv2.imread('lena.jpg', cv2.IMREAD_COLOR)

cv2.imread(fileName, flag)
flag .
Parameters
• fileName (str) –
• flag (int) – Option.
Returns image
Return type numpy.ndarray
flag 3 .
• cv2.IMREAD_COLOR : Color . , Default.
• cv2.IMREAD_GRAYSCALE : Grayscale . .
• cv2.IMREAD_UNCHANGED : alpha channel .

Note: 3 flag 1, 0, -1 .

img numpy ndarray type. numpy python openCV . img .


>>> img.shape
(206, 207, 3)

3 return . 206 (Y), 207 (X), 3 . 207 X 206 .


3 . BGR. RGB , openCV B(lue), G(reen), R(ed) .

3
OpenCV Python Documentation, Release 0.1

1.3
cv2.imshow() .
>>> c22.imshow('image', img)
>>> cv2.waitKey(0)
>>> cv2.destroyAllWindows()

cv2.imshow(title, image)
.
Parameters
• title (str) – Title
• image (numpy.ndarray) – cv2.imread() return
cv2.waitKey() keyboard 0 key milisecond .
cv2.destroyAllWindows() . 3 .
Sample Code
1 import cv2
2

3 fname = 'lena.jpg'
4

5 original = cv2.imread(fname, cv2.IMREAD_COLOR)


6 gray = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
7 unchange = cv2.imread(fname, cv2.IMREAD_UNCHANGED)
8

9 cv2.imshow('Original', original)
10 cv2.imshow('Gray', gray)
11 cv2.imshow('Unchange', unchange)
12

13 cv2.waitKey(0)
14 cv2.destroyAllWindows()

Fig. 1.1: Sample Image

flag .

4 Chapter 1.
OpenCV Python Documentation, Release 0.1

Fig. 1.2: Original

Fig. 1.3: Grayscale

Fig. 1.4: Unchange

1.3. 5
OpenCV Python Documentation, Release 0.1

1.4
cv2.imwrite() .
>>> cv2.imwrite('lenagray.png', gray)

cv2.imwrite(fileName, image)
image .
Parameters
• fileName (str) –
• image –
Sample Code
esc , ‘s’ key grayscale Sample. cv2.waitKey() .:
import cv2

img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)


cv2.imshow('image',img)
k = cv2.waitKey(0)
if k == 27: # esc key
cv2.destroyAllWindow()
elif k = ord('s'): # 's' key
cv2.imwrite('lenagray.png',img)
cv2.destroyAllWindow()

Warning: 64bit OS k = cv2.waitKey(0) & 0xFF bit .

1.5 Matplotlib

Matplotlib plot Python Plot Library. zoom .


Sample Code
1 #-*- coding:utf-8 -*-
2 import cv2
3 from matplotlib import pyplot as plt # as alias
4

5 img = cv2.imread('lena.jpg', cv2.IMREAD_COLOR)


6

7 plt.imshow(img)
8 plt.xticks([]) # x
9 plt.yticks([]) # y
10 plt.show()

Result
. , .
openCV BGR , Matplotlib RGB .
3 .
Sample .
Sample Code
1 #-*- coding:utf-8 -*-
2 import cv2
3 from matplotlib import pyplot as plt # as alias

6 Chapter 1.
OpenCV Python Documentation, Release 0.1

Fig. 1.5: Matplotlib Result

1.5. Matplotlib 7
OpenCV Python Documentation, Release 0.1

5 img = cv2.imread('lena.jpg', cv2.IMREAD_COLOR)


6

7 b, g, r = cv2.split(img) # img b,g,r


8 img2 = cv2.merge([r,g,b]) # b, r Merge
9

10 plt.imshow(img2)
11 plt.xticks([]) # x
12 plt.yticks([]) # y
13 plt.show()

Result

Fig. 1.6: RGB

8 Chapter 1.
CHAPTER 2

2.1 Goal
• ,, .
• cv2.VideoCapure() , cv2.VideoWriter() .

2.2 Camera

Camera , .
• VideoCapture Object . camera device index . 0 Camera .
• Loop frame .
• frame , .
• , VideoCapure Object release window .
grayscale .
Sample Code
1 # -*-coding: utf-8 -*-
2 import cv2
3

4 # cap open cap.isOpen()


5 cap = cv2.VideoCapture(0)
6

7 # cap.get(prodId)/cap.set(propId, value) .
8 # 3 width, 4 heigh
9

10 print 'width: {0}, height: {1}'.format(cap.get(3),cap.get(4))


11 cap.set(3,320)
12 cap.set(4,240)
13

14 while(True):
15 # ret : frame capture(boolean)
16 # frame : Capture frame
17 ret, frame = cap.read()
18

19 if (ret):
20 # image Grayscale Convert.
21 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
22

23 cv2.imshow('frame', gray)
24 if cv2.waitKey(1) & 0xFF == ord('q'):
25 break

9
OpenCV Python Documentation, Release 0.1

26

27 cap.release()
28 cv2.destroyAllWindows()

2.3 File

File Camera .
Sample Code
1 import cv2
2

3 cap = cv2.VideoCapture('vtest.avi')
4

5 while(cap.isOpened()):
6 ret, frame = cap.read()
7 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
8 cv2.imshow('frame',gray)
9

10 if cv2.waitKey(1) & 0xFF == ord('q'):


11 break
12 cap.release()
13 cv2.destroyAllWindows()

Note: Codec .

2.4

cv2.VideoWriter Object .
cv2.VideoWriter(outputFile, fourcc, frame, size)
Object
Parameters
• outputFile (str) –
• fourcc – Codec. cv2.VideoWriter_fourcc()
• frame (float) – frame
• size (list) – (ex; 640, 480)
fourcc cv2.VideoWriter_fourcc(’M’,’J’,’P’,’G’) cv2.VideoWriter_fourcc(*’MJPG)
. OS codec .(Windows DIVX)
Sample Code
1 # -*-coding: utf-8 -*-
2

3 import cv2
4

5 cap = cv2.VideoCapture(0)
6

7 fourcc = cv2.VideoWriter_fourcc(*'DIVX')
8 out = cv2.ViewoWriter('output.avi', fourcc, 25.0, (640,480))
9

10 while (cap.isOpend()):
11 ret, frame = cap.read()
12

10 Chapter 2.
OpenCV Python Documentation, Release 0.1

13 if ret:
14 # , 0:, 1 :
15 frame = cv2.flip(frame, 0)
16

17 out.write(frame)
18

19 cv2.imshow('frame', frame)
20

21 if cv2.waitKey(0) & 0xFF == ord('q'):


22 break
23 else:
24 break
25

26 cap.release()
27 out.release()
28 cv2.destroyAllWindows()

2.4. 11
OpenCV Python Documentation, Release 0.1

12 Chapter 2.
CHAPTER 3

3.1 Goal
• .
• cv2.line() , cv2.circle() , cv2.rectangle() , cv2.putText() .
Match .

3.2 Line

Start End .
cv2.line(img, start, end, color, thickness)
Parameters
• img –
• start – (ex; (0,0))
• end – (ex; (500. 500))
• color – BGR Color(ex; (255, 0, 0) -> Blue)
• thickness (int) – . pixel
Sample Code
1 import numpy as np
2 import cv2
3

4 # 0 Canvas()
5 img = np.zeros((512, 512, 3), np.uint8)
6 img = cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
7

8 cv2.imshow('image',img)
9 cv2.waitKey(0)
10 cv2.destroyAllWindows()

3.3

top-left corner bottom-right corner .


cv2.rectangle(img, start, end, color, thickness)
Parameters

13
OpenCV Python Documentation, Release 0.1

• img –
• start – (ex; (0,0))
• end – (ex; (500. 500))
• color – BGR Color(ex; (255, 0, 0) -> Blue)
• thickness (int) – . pixel
Sample Code
img = cv2.rectangle(img, (384, 0), (510, 128), (0,255,0), 3)

3.4

cv2.circle(img, center, radian, color, thickness)


Parameters
• img –
• center – (x, y)
• radian –
• color – BGR Color
• thickness – , -1
Sample Code
img = cv2.circle(img, (447,63), 63, (0,0,255), -1)

3.5

cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType


Parameters
• img – image
• center –
• axes –
• angle –
• startAngle –
• endAngle –
• color –
• thickness – -1
Sample Code
img = cv2.ellipse(img, (256,256), (100,50), 0, 0, 180, 255, -1)

3.6 Polygon

cv2.polylines(img, pts, isClosed, color, thickness)


Parameters

14 Chapter 3.
OpenCV Python Documentation, Release 0.1

• img – image
• pts (array) –
• isClosed –
• color – Color
• thickness –
Sample Code
pts = np.array([[10,5], [20,30], [70,20], [50,10]], np.int32) # 2
# 3 . .
# -1 .
pts = pts.reshape((-1, 1, 2))
img = cv2.polylines(img, [pts], True, (0,255,255))

3.7 Text

cv2.putText(img, text, org, font, fontSacle, color)


Parameters
• img – image
• text –
• org – . bottom-left corner
• font – font type. CV2.FONT_XXX
• fontSacle – Font Size
• color – fond color
Sample Code
cv2.putText(img, 'OpenCV', (10,500), cv2.FONT_HERSHEY_SIMPLEX, 4, (255,255,255), 2)

Sample Code .

3.7. Text 15
OpenCV Python Documentation, Release 0.1

16 Chapter 3.
CHAPTER 4

Mouse

4.1 Goal
• Mouse Event .
• cv2.setMouseCallback() .

4.2

OpenCV Mouse Event . Python Terminal .


>>> import cv2
>>> events = [i for i in dir(cv2) if 'EVENT' in i]
>>> print events

Mouse Event . Event .:


'EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG

Mouse Event Callback cv2.setMouseCallback() .


cv2.setMouseCallback(windowName, callback, param=None)
Parameters
• windowName – windowName
• callback – callback. callback (event, x, y, flags, param) .
• param – callback Data

4.3 Demo

Demo Double-Click .
1 import cv2
2 import numpy as np
3

4 # callback
5 def draw_circle(event, x, y, flags, param):
6 if event == cv2.EVENT_LBUTTONDBLCLK:
7 cv2.circle(img,(x,y), 100,(255,0,0),-1)
8

9 # Image
10 img = np.zeros((512,512,3), np.uint8)
11 cv2.namedWindow('image')

17
OpenCV Python Documentation, Release 0.1

12 cv2.setMouseCallback('image', draw_circle)
13

14 while(1):
15 cv2.imshow('image', img)
16 if cv2.waitKey(0) & 0xFF == 27:
17 break
18

19 cv2.destroyAllWindows()

4.4 Advanced Demo

Demo. Segmentaion .(ex; )


1 #-*- coding:utf-8 -*-
2 import cv2
3 import numpy as np
4

5 drawing = False #Mouse


6 mode = True # True , false
7 ix,iy = -1,-1
8

10 # Mouse Callback
11 def draw_circle(event, x,y, flags, param):
12 global ix,iy, drawing, mode
13

14 if event == cv2.EVENT_LBUTTONDOWN: #
15 drawing = True
16 ix, iy = x,y
17 elif event == cv2.EVENT_MOUSEMOVE: #
18 if drawing == True: #
19 if mode == True:
20 cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
21 else:
22 cv2.circle(img,(x,y),5,(0,255,0),-1)
23

24 elif event == cv2.EVENT_LBUTTONUP:


25 drawing = False; #
26 if mode == True:
27 cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
28 else:
29 cv2.circle(img,(x,y),5,(0,255,0),-1)
30

31

32 img = np.zeros((512,512,3), np.uint8)


33 cv2.namedWindow('image')
34 cv2.setMouseCallback('image',draw_circle)
35

36 while True:
37 cv2.imshow('image', img)
38

39 k = cv2.waitKey(1) & 0xFF


40

41 if k == ord('m'): # , Mode
42 mode = not mode
43 elif k == 27: # esc
44 break
45

46 cv2.destroyAllWindows()
47

18 Chapter 4. Mouse
CHAPTER 5

Trackbar

5.1 Goal

• trackbar OpenCV .
• cv2.getTrackbarPos() , cv2.createTrackbar() .

5.2 Demo

Trackbar Demo . Demo 4 Tranckbar . 3 RGB , .


Demo cv2.getTrackbarPos() , cv2.createTrackbar() .
cv2.createTrackbar(trackbarName, windowName, value, count, onChange)
Parameters
• trackbarName – trackbar Name
• windowName – Named Window
• value (int) – Trackbar
• count – Tracbar Max. Min 0
• onChange – Slide Callback. Paramter trackbar Position
cv2.getTrackbarPos(trackbarName, windowName)
Parameters
• trackbarName – trackbar Name
• windowName – Trackbar Named Window
Sample Code
1 #-*- coding: utf-8 -*-
2 import cv2
3 import numpy as np
4

5 def nothing(x):
6 pass
7

8 img = np.zeros((300,512,3), np.uint8)


9 cv2.namedWindow('image')
10

11 # trackbar named window


12 cv2.createTrackbar('R', 'image', 0, 255, nothing)
13 cv2.createTrackbar('G', 'image', 0, 255, nothing)

19
OpenCV Python Documentation, Release 0.1

14 cv2.createTrackbar('B', 'image', 0, 255, nothing)


15

16 switch = '0:OFF\n1:On'
17 cv2.createTrackbar(switch, 'image', 1, 1, nothing)
18

19 while(1):
20 cv2.imshow('image', img)
21

22 if cv2.waitKey(1) & 0xFF == 27:


23 break
24

25 r = cv2.getTrackbarPos('R','image')
26 g = cv2.getTrackbarPos('G', 'image')
27 b = cv2.getTrackbarPos('B', 'image')
28 s = cv2.getTrackbarPos(switch, 'image')
29

30 if s == 0:
31 img[:] = 0 # / 0 .
32 else:
33 img[:] = [b,g,r] # / [b,g,r]
34

35 cv2.destroyAllWindows()

20 Chapter 5. Trackbar
CHAPTER 6

Indices and tables

• genindex
• modindex
• search

21
OpenCV Python Documentation, Release 0.1

22 Chapter 6. Indices and tables


Index

C
cv2.circle() (built-in function), 14
cv2.createTrackbar() (built-in function), 19
cv2.getTrackbarPos() (built-in function), 19
cv2.imread() (built-in function), 3
cv2.imshow() (built-in function), 4
cv2.imwrite() (built-in function), 6
cv2.line() (built-in function), 13
cv2.polylines() (built-in function), 14
cv2.putText() (built-in function), 15
cv2.rectangle() (built-in function), 13
cv2.setMouseCallback() (built-in function), 17
cv2.VideoWriter() (built-in function), 10

23

You might also like