color masking with openCV

Install:

conda create --name opencv --file package-list.txt

Use:

source activate opencv

Photo from http://www.jbcharleston.jb.mil/News/Photos/igphoto/2000417879/ under Public Domain

In [60]:
import matplotlib.pyplot as plt
import numpy as np
import cv2
%matplotlib inline
In [115]:
image = cv2.imread('stopsign.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (300, 200)) 
original = np.copy(image)
plt.imshow(image)
Out[115]:
<matplotlib.image.AxesImage at 0x119b06790>
In [116]:
lower_red = np.array([100,0,0]) 
upper_red = np.array([255,50,80])

# Mask the image 
masked_image = np.copy(image)
mask = cv2.inRange(masked_image, lower_red, upper_red)

masked_image[np.where(mask > 0)] = [0, 255, 0]

# Display it
plt.subplot(121)
plt.imshow(original)
plt.subplot(122)
plt.imshow(masked_image)
Out[116]:
<matplotlib.image.AxesImage at 0x1234c8550>

image warping on business card

Image taken from https://www.flickr.com/photos/26158205@N04/5123561523 under CC BY-SA 2.0

In [112]:
image = cv2.imread('business_card.png')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
original = np.copy(image)
plt.imshow(image)
Out[112]:
<matplotlib.image.AxesImage at 0x1141db790>
In [64]:
# define corner points in original image to straighten out
original_points = np.float32([
    [-50, 170],
    [80, 470],
    [580, 300],
    [475, 35]
])

plt.imshow(image)

for p in original_points:
    plt.plot(p[0], p[1], 'o')
In [65]:
# define target points to transform to
target_width = 600
target_height = 350
target_points = np.float32([
    [0, 0],
    [0, target_height],
    [target_width, target_height],
    [target_width, 0]
])
In [66]:
# define transformation matrix
M = cv2.getPerspectiveTransform(original_points, target_points)
print(M)
[[  9.14525308e-01  -3.96294300e-01   1.13096296e+02]
 [  2.69503092e-01   1.04806758e+00  -1.64696334e+02]
 [ -2.35604047e-04   3.67938539e-05   1.00000000e+00]]
In [114]:
# transform & plot
plt.subplot(121)
plt.imshow(original)

plt.subplot(122)
image_size = (image.shape[1], image.shape[0])
transformed = cv2.warpPerspective(image, M, image_size, flags=cv2.INTER_LINEAR)
plt.imshow(transformed)
Out[114]:
<matplotlib.image.AxesImage at 0x119261850>
In [103]:
image = cv2.imread('torturm.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (400, 600)) 

original = np.copy(image)
plt.imshow(image)
Out[103]:
<matplotlib.image.AxesImage at 0x124def450>
In [104]:
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
plt.figure(figsize=(14, 9))
plt.imshow(gray, cmap='gray')
Out[104]:
<matplotlib.image.AxesImage at 0x12983cad0>