import cv2 as cv
# Open the video camera no.0
cap = cv.VideoCapture(0)
# If not success, exit the program
if not cap.isOpened():
print('Cannot open camera')
cv.namedWindow('MyVideo', cv.WINDOW_AUTOSIZE)
while True:
# Read a new frame from video
ret, frame = cap.read()
# If not success, break loop
if not ret:
print('Cannot read frame')
break
cv.imshow('MyVideo', frame)
if cv.waitKey(30) & 0xFF == 27:
print('Press ESC to stop')
break
cv.destroyAllWindows()
cap.release()
(*.ipyn) Read / Write / Display Image and Video
Import OpenCV Library
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
(for COLAB only) Upload Image Files in Colab server
Skip this if you are using Visual Studio Code
Read how to load image file in Colab
Other Option: Upload image file to Colab server from local drive
from google.colab import files
uploaded=files.upload()
This tutorial will use matplotlib functions for *.ipyn files. This method is recommended for showing images. This works for both *.py and *.ipyn files.
# Load image
img = cv.imread('Image/sudoku.jpg',0) # Gray scale image
# Canny Edge Detection
dst = cv.Canny(img, 50, 200, None, 3)
# Copy edges to the images that will display the results in BGR
cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
cdstP = np.copy(cdst)
# (Option 1) HoughLines
lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)
if lines is not None:
for i in range(0, len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)
# (Option 2) HoughLinesP
linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10)
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA)
# Plot Results
#cv.imshow("Source", img)
#cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)
#cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)
titles = ['Source','Standard H.T','Prob. H.T']
images = [img, cdst, cdstP]
for i in range(3):
plt.subplot(1,3,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
Exercise
Beginner Level Exercise
Exercise 1
Apply Blur filters, Thresholding and Morphology methods on given images for object segmentation.
Example 2
Choose the appropriate InRange conditions to segment only ' Blue colored ball'. Draw the contour and a box over the target object. Repeat for Red, and Yellow balls
Example 3
Detect Pupil/Iris and draw circles.
Intermediate Level Exercise
Exercise: Count number of coins and calculate the total amount
After applying thresholding and morphology, we can identify and extract the target objects from the background by finding the contours around the connected pixels. This technique is used where you need to monitor the number of objects moving on a conveyor belt in an industry process. Goal: Count the number of the individual coins and calculate the total amount of money.
Procedure:
Apply a filter to remove image noises
Choose the appropriate threshold value.
Apply the appropriate morphology method to segment coins
Find the contour and draw the segmented objects.
Exclude the contours which are too small or too big
Count the number of each different coins(10/50/100/500 won)