OpenCV in Python



By Prof. Seungchul Lee
http://iai.postech.ac.kr/
Industrial AI Lab at POSTECH

Table of Contents

1. Working with Images¶

1.1. Using OpenCV¶

The preceding script imports an image, displays it (pop up), and waits for a keystroke to close the window. The screenshot is as follows:

Download image data

In [1]:
import cv2

img = cv2.imread('./data_files/lena_color_512.tif', 1)
cv2.imshow('Lena',img)
cv2.waitKey(0)
cv2.destroyWindow('Lena')

1.2. Using matplotlib¶

In [2]:
import matplotlib.pyplot as plt
%matplotlib inline

# Program to load a color image in gray scale and to display using matplotlib
img = cv2.imread('./data_files/lena_color_512.tif', 0)
plt.imshow(img,cmap = 'gray')
plt.title('Lena')
plt.xticks([])
plt.yticks([])
plt.show()

1.3. Drawing geometric shapes¶

In [3]:
import numpy as np

image = np.zeros((200,200,3), np.uint8)

cv2.line(image,(0,199),(199,0),(0,0,255),2)
cv2.rectangle(image,(20,20),(60,60),(255,0,0),1)
cv2.circle(image,(80,80),10,(0,255,0),-1)
cv2.ellipse(image,(99,99),(40,20),0,0,360,(128,128,128),-1)

points = np.array([[100,5],[125,30],[175,20],[185,10]], np.int32)
points = points.reshape((-1,1,2))

cv2.polylines(image,[points],True,(255,255,0))
cv2.putText(image,'Test',(80,180),cv2.FONT_HERSHEY_DUPLEX,1, (255,0,255))
cv2.imshow('Shapes',image)

cv2.waitKey(0)
cv2.destroyAllWindows()

1.4. Working with trackbar and named window¶

In [4]:
def empty(z):
    pass

# Create a black background
image = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('Palette')
# create trackbars for colors and associate those with Pallete
cv2.createTrackbar('B','Palette',0,255,empty)
cv2.createTrackbar('G','Palette',0,255,empty)
cv2.createTrackbar('R','Palette',0,255,empty)

while(True):
    cv2.imshow('Palette',image)
    if cv2.waitKey(1) == 27:
        break

    # fetch the color value
    blue = cv2.getTrackbarPos('B','Palette')
    green = cv2.getTrackbarPos('G','Palette')
    red = cv2.getTrackbarPos('R','Palette')
    image[:] = [blue,green,red]
    
cv2.destroyWindow('Pallete')

1.5. Working with a webcam¶

1.5.1. Capturing an image from a webcam using OpenCV¶

In [5]:
# initialize the camera

cam = cv2.VideoCapture(0)
ret, image = cam.read()

if ret:
    cv2.imshow('SnapshotTest',image)
    cv2.waitKey(0)
    cv2.destroyWindow('SnapshotTest')
    
cam.release()

1.5.2. Display a live video stream and a modificated frame size¶

In [6]:
cam = cv2.VideoCapture(0)
print("Default Resolution is " + str(int(cam.get(3))) + "x" + str(int(cam.get(4))))

w=320
h=240
cam.set(3,w)
cam.set(4,h)

print("Now resolution is set to " + str(w) + "x" + str(h))

while(True):
    # Capture frame-by-frame
    ret, frame = cam.read()
    # Display the resulting frame
    cv2.imshow('Video Test',frame)
    # Wait for Escape Key
    if cv2.waitKey(1) == 27 :
        break
# When everything done, release the capture
cam.release()
cv2.destroyAllWindows()
Default Resolution is 640x480
Now resolution is set to 320x240

1.5.3. Saving a video¶

VideoWriter function is changed in new version of OpenCV.

In [7]:
cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'WMV2')
output = cv2.VideoWriter('D:/VideoStream.avi',fourcc,40.0,(640,480))

while (cam.isOpened()):
    ret, frame = cam.read()
    if ret == True:
        output.write(frame)
        cv2.imshow('VideoStream', frame )
        if cv2.waitKey(1) == 27 :
            break
    else:
        break
            
cam.release()
output.release()
cv2.destroyAllWindows()

2. Basic Image Processing¶

2.1. Arithmetic operations on images¶

In [8]:
img1 = cv2.imread('./data_files/lena_color_512.tif',1)
img2 = cv2.imread('./data_files/mandril_color.tif',1)

cv2.imshow('Lena',img1)
cv2.waitKey(0)

cv2.imshow('Mandril',img2)
cv2.waitKey(0)

cv2.imshow('Addition',cv2.add(img1,img2))
cv2.waitKey(0)

cv2.imshow('Lena-Mandril',cv2.subtract(img1,img2))
cv2.waitKey(0)

cv2.imshow('Mandril-Lena',cv2.subtract(img2,img1))
cv2.waitKey(0)

cv2.destroyAllWindows()