Line Detection of the break between two different spectra


In [1]:
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('doublespectrum.png', 1)

OpenCV image display doesn't seem to work in the notebook: it insists on popping up a window that then can't be closed, without killing the kernel. So, we're displaying images with matplotlib instead. However, OpenCV loads in BGR mode, but Matplotlib displays in RGB mode, so images will be displayed with red and blue reversed.


In [2]:
# Show image with matplotlib
plt.imshow(img)
plt.xticks([]), plt.yticks([])
plt.show()



In [3]:
print img.shape
print img.size
print img.dtype


(112, 275, 3)
92400
uint8

In [4]:
# Splitting and merging to fix the colour mode issue.
b,g,r = cv2.split(img)
img2 = cv2.merge((r,g,b))

In [5]:
plt.imshow(img2)
plt.xticks([]), plt.yticks([])
plt.show()



In [6]:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

In [7]:
plt.imshow(gray, cmap = 'gray')
plt.xticks([]), plt.yticks([])
plt.show()



In [9]:
print gray.shape


(112, 275)

In [10]:
plt.plot(gray[56,:])
plt.show()



In [11]:
plt.plot(gray[60,:])
plt.show()



In [12]:
plt.plot(gray[65,:])
plt.show()



In [13]:
plt.plot(gray[:,115])
plt.show()



In [16]:
plt.plot(gray)
plt.show()



In [22]:
x = sum(gray,1)
print x.shape


(112,)

In [24]:
plt.plot(x)
plt.show()



In [51]:
from scipy.signal import argrelextrema
mins = argrelextrema(x, np.less)
print mins[0]


[11 24 43 47 62 85]

In [38]:
plt.plot(gray[62,:])
plt.show()


Find local minimum closest to midpoint of the region (i.e. closest to 56)


In [52]:
distances = [abs(minimum - 56) for minimum in mins[0]]
print distances


[45, 32, 13, 9, 6, 29]

In [53]:
min_dist = min(distances)
print min_dist


6

In [57]:
index = distances.index(min_dist)
dividing_line = mins[0][index]

In [58]:
print dividing_line


62

In [63]:
# Top spectrum
plt.imshow(img2[:dividing_line,:,:])
plt.xticks([]), plt.yticks([])
plt.show()



In [64]:
# Bottom spectrum
plt.imshow(img2[dividing_line:,:,:])
plt.xticks([]), plt.yticks([])
plt.show()



In [ ]: