import numpy as np
import cv2
import sys
import matplotlib.pyplot as plt
# Source: http://www.mattmahoney.net/ocr/
image1_path = "/work/NASDAQ_Example.jpg"
img1 = cv2.cvtColor(cv2.imread(image1_path), cv2.COLOR_BGR2RGB)
Regular Thresholding
thresh
164 / 255
fig, ax = plt.subplots(1, 2, figsize=(20, 10))
ax[0].imshow(img1)
timg1 = (img1 < thresh).astype(np.uint8)*255
ax[1].imshow(timg1)
Morphological Operators
kernel_width
12 / 100
img2 = np.zeros((480, 640, 3), dtype=np.uint8)
img2[100:200,100:300] = 255
img2[180:380,280:480] = 255
img2[240:320,340:420] = 0
fig, ax = plt.subplots(1, 3, figsize=(40, 10))
ax[0].imshow(img2)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(kernel_width, kernel_width))
img2_dilate = cv2.dilate(img2, kernel)
img2_erode = cv2.erode(img2, kernel)
ax[1].imshow(img2_dilate)
ax[2].imshow(img2_erode)
kernel_width2
2 / 10
# Downsize image
img1_noise = img1[::2, ::2, :].copy()
shape = img1_noise.shape
# Add noise
for _ in range(200):
i, j = np.random.randint(shape[0]-2), np.random.randint(shape[1]-2)
img1_noise[i:i+1, j:j+2] = 0
for _ in range(200):
i, j = np.random.randint(shape[0]-2), np.random.randint(shape[1]-2)
img1_noise[i:i+1, j:j+2] = 255
fig, ax = plt.subplots(1, 2, figsize=(20, 10))
ax[0].imshow(img1_noise)
timg_noise1 = (img1_noise < thresh).astype(np.uint8)*255
ax[1].imshow(timg_noise1)
# Morphological operators
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(kernel_width2, kernel_width2))
timg_noise1_dilate = cv2.dilate(timg_noise1, kernel)
timg_noise1_erode = cv2.erode(timg_noise1, kernel)
fig, ax = plt.subplots(1, 2, figsize=(20, 10))
ax[0].imshow(timg_noise1_dilate)
ax[1].imshow(timg_noise1_erode)
Filtering - Blurring
blur_radius
45 / 100
# Image source: https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Purple_osteospermum.JPG/1599px-Purple_osteospermum.JPG
image1_path = "/work/osteospermum.jpeg"
# Image source: https://www.cs.rochester.edu/~brown/449/assts/fruit_tray.gif
image2_path = "/work/fruit_tray.jpeg"
img3 = cv2.cvtColor(cv2.imread(image1_path), cv2.COLOR_BGR2RGB)
img4 = cv2.cvtColor(cv2.imread(image2_path), cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(1, 2, figsize=(20, 10))
ax[0].imshow(img3)
ax[1].imshow(img4)
blur_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(blur_radius, blur_radius))
blur_kernel = blur_kernel / np.sum(np.abs(blur_kernel))
fig, ax = plt.subplots(1, 2, figsize=(20, 10))
ax[0].imshow(cv2.filter2D(img3, -1, blur_kernel))
ax[1].imshow(cv2.filter2D(img4, -1, blur_kernel))