OpenCV Tutorial
March 22, 2021
1 Import
In [1]: import cv2
2 Read Image
In [17]: image = [Link]("[Link]")
3 Get width and height
In [18]: (h, w, d) = [Link]
print(f"width = {w}, height = {h}, depth = {d}")
width = 2048, height = 1316, depth = 3
4 Showing an image
In [23]: [Link]("Image", image)
[Link](10000)
[Link]()
5 BGR Colour Space
In [25]: (B, G, R) = image[100, 50]
print(f"R = {R}, G = {G}, B = {B}")
R = 209, G = 217, B = 194
6 ROI
In [29]: roi = image[100:500, 50:450]
[Link]("ROI", roi)
[Link](10000)
[Link]()
1
7 Resize
In [32]: resized = [Link](image, (500, 500))
[Link]("Fixed Resize", resized)
[Link](10000)
[Link]()
In [33]: fixed_width = 500
ratio = fixed_width/w
aspect_resize = [Link](image, (fixed_width, int(h*ratio)))
[Link]("Aspect Resize", aspect_resize)
[Link](10000)
[Link]()
8 Rotate
In [35]: center = (w//2, h//2)
M = cv2.getRotationMatrix2D(center, -45, 1.0)
rotated = [Link](image, M, (w, h))
[Link]("Rotated", rotated)
[Link](10000)
[Link]()
9 Smoothing
In [42]: blurred = [Link](image, (25, 25), 0)
[Link]("Blurred", blurred)
[Link](10000)
[Link]()
10 Drawing
In [43]: output = [Link]()
[Link](output, (200, 300), (500, 800), (0, 0, 255), 2)
[Link]("Rectangle", output)
[Link](10000)
[Link]()
In [44]: output = [Link]()
[Link](output, (200, 300), 100, (0, 255, 0), -1)
[Link]("Circle", output)
[Link](10000)
[Link]()
In [45]: output = [Link]()
[Link](output, (200, 300), (500, 800), (255, 0, 0), 2)
[Link]("Line", output)
2
[Link](10000)
[Link]()
In [48]: output = [Link]()
[Link](output, "Hello Jurrasic Park!", (300, 300), cv2.FONT_HERSHEY_SIMPLEX, 3, (
[Link]("Text", output)
[Link](10000)
[Link]()