# Convert jupyter notebook to python script:
#!jupyter nbconvert --to script file-name.ipynb
#$ python file-name.py --image01 image01.png --image02 image02.png --image03 image03.png
# in ap.add_arrgument use : required = True + remove default path
#args = vars(ap.parse_args())
import numpy as np
import cv2
import argparse
import matplotlib.pyplot as plt
ap = argparse.ArgumentParser(description='Fooo')
ap.add_argument("-i1", "--image01",
                default = "images/face_detection05.jpg", required=False,# for *.py use required= True
    help="path to input image")
ap.add_argument("-i2", "--image02",
                default = "images/green.jpg", required=False,# for *.py use required= True
    help="path to input image")
ap.add_argument("-i3", "--image03",
                default = "images/tetris_blocks.png", required=False,# for *.py use required= True
    help="path to input image")
args = vars(ap.parse_args([])) #for *.py use args = vars(ap.parse_args())

1. Loading / Displaying an image

image = args["image01"]
image = cv2.imread(image)#imread(args["image"])
(h, w, c) = image.shape
for i in range(1):    
    fig = plt.figure("My Image", figsize = (7, 5))
    ax = fig.add_subplot(111)
    plt.imshow(image, cmap = plt.cm.gray)
    plt.axis("off")    
    #plt.suptitle("My Image")
#cv2.imshow("Image", image)
#cv2.waitKey(0)
plt.imshow(image)
<matplotlib.image.AxesImage at 0x7f1e5a6fb850>

2. Accesing Individual Pixels

# OpenCV stores images in BGR order rather than RGB
(B, G, R) = image[100, 50]
print("R={}, G={}, B={}".format(R, G, B))
R=119, G=118, B=116

3. Array slicing/cropping

  • it is useful when extracting ROI (Region of Interest)
# input image starting at x=320,y=60 at ending at x=420,y=160
roi = image[200:600, 0:500]
plt.imshow(roi)#cv2.imshow("ROI", roi)cv2.waitKey(0)
<matplotlib.image.AxesImage at 0x7f1e38247ad0>

4. Resizing an image

  • In the case of deep learning, we often resize images, ignoring aspect ratio, so that the volume fits into a network which requires that an image be square and of a certain dimension.
resized = cv2.resize(image, (300, 300))
plt.imshow(resized)
<matplotlib.image.AxesImage at 0x7f1e381860d0>
#and calculate new height based on aspect-ratio in original image.
r = 300.0 / w # ratio of old width /new width
dim = (300, int(h * r))
resized = cv2.resize(image, dim)
plt.imshow(resized)
<matplotlib.image.AxesImage at 0x7f1e32db2710>

5. Rotating an image

  • Check imutils by pyimagesearch if you want to avoid croping the edges
center = (w // 2, h // 2)
#Rotating an image about the center point requires that we first calculate the center (x, y)-coordinates of the image
#//to perform integer math
#rotate image 45 deg clockwise
M = cv2.getRotationMatrix2D(center, 45, 1.0)
#we warp the image using the matrix (effectively rotating it)
rotated = cv2.warpAffine(image, M, (w, h))
plt.imshow(rotated)
#cv2.imshow("OpenCV Rotation", rotated)
#cv2.waitKey(0)
<matplotlib.image.AxesImage at 0x7f1e381a03d0>

6. Smoothing an image

  • Bluring an image reduces high-frequency noise, making it easier for NN algorithms to detect and understand the actual contents of the image rather than just noise that will “confuse” our algorithms.
# larger kernel will give blurrier image
blurred = cv2.GaussianBlur(image, (25, 25), 0)
plt.imshow(blurred)
<matplotlib.image.AxesImage at 0x7f1e3115ed90>

6. Drawing on an image

output = image.copy()
# output: image to be drawn on
# (x, y): top-left coordinates of rectangle
# (x, y): right-bottom coordinates of rectangle
cv2.rectangle(output, (200, 200), (600, 600), (255, 0, 240), 5)
cv2.rectangle(output, (0, 200), (200, 400), (50, 205, 50), 5)
cv2.circle(output, (1000, 700), 30, (255, 0, 0), -1)
cv2.line(output, (800, 830), (800, 100), (255, 0, 0), 5)
plt.imshow(output)
<matplotlib.image.AxesImage at 0x7f1e30b6f810>
output = image.copy()
FONT_SIZE = 3
COLOR = (0, 255, 0)
LINE_W = 2
LOC = (100, 100)
PROB = 0.9
LOC2 = (200, 200)
cv2.putText(output, "1992: M + B + T", LOC, cv2.FONT_HERSHEY_SIMPLEX, FONT_SIZE, COLOR, LINE_W)
cv2.putText(output, "{:.2f}".format(PROB), LOC2, cv2.FONT_HERSHEY_SIMPLEX, FONT_SIZE, COLOR, LINE_W)
plt.imshow(output)
<matplotlib.image.AxesImage at 0x7fec79c6e850>

7.Converting an image to grayscale

  • channels = 1
  • NN transform 1 channels to 3 for input in NN
image = args["image02"]#"images/green.jpg"
image = cv2.imread(image)
norm = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#fig = plt.figure(figsize = (10, 10))
#ax = fig.add_subplot(131)
#ax.set_title("BGR")
#plt.imshow(image)
##plt.axis("off")
#ax = fig.add_subplot(132)
#plt.imshow(norm)
#plt.axis("off")
#ax.set_title("RGB")
##plt.colorbar()
#ax = fig.add_subplot(133)
#ax.set_title("GRAY")
#plt.imshow(gray)
##plt.axis("off")
##plt.colorbar()
fig = plt.figure(figsize = (10,10))
images = ("BGR", image), ("RGB", norm), ("GRAY", gray)
# loop over the images
for (i, (name, image)) in enumerate(images):
    # show the image
    ax = fig.add_subplot(1, 3, i + 1)
    ax.set_title(name)
    plt.imshow(image, cmap = "gray")
    plt.axis("off")

8. Perform edge detection

image = args["image03"]
image = cv2.imread(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(gray, cmap = "gray")
<matplotlib.image.AxesImage at 0x7f1e180c8ed0>
edged_d = cv2.Canny(gray, 4, 150)
edged_c = cv2.Canny(gray, 100, 150)
images = ("Coarse", edged_c), ("Detailed", edged_d)
fig = plt.figure(figsize = (10, 10))
for i , (name, image) in enumerate(images):
    ax = fig.add_subplot(1,2, i+1)
    ax.set_title(name)
    plt.imshow(image, cmap = "gray")
    plt.axis("off")

9. Thresholding a grayscale image

thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1]
plt.imshow(thresh, cmap = "gray")
<matplotlib.image.AxesImage at 0x7f1e18380b10>

10. Erosions and dilations

  • Errode away pixels to make smoother edges
mask = thresh.copy()
mask = cv2.erode(mask, None, iterations=5)
plt.imshow(mask, cmap = "gray")
<matplotlib.image.AxesImage at 0x7f1e18029150>

11.Detecting and drawing contours

  • to be continued

12. Save a file name

i = 0
plt.imshow(image)
filename = "images/cv2_tut/my_image_"+"{:02d}".format(i) +".jpg"
cv2.imwrite(filename, image)
True