In [1]:
import cv2
img = cv2.imread('images/ruler.png')
gray = cv2.imread('images/ruler.png', cv2.CV_LOAD_IMAGE_GRAYSCALE)
plt.figsize(8,8) # adjust scaling of images displayed in IPython

In [2]:
thresholds = [cv2.THRESH_BINARY,
              cv2.THRESH_BINARY_INV,
              # cv2.THRESH_MASK,
              cv2.THRESH_OTSU,
              cv2.THRESH_TOZERO,
              cv2.THRESH_TOZERO_INV,
              cv2.THRESH_TRUNC]

In [3]:
def extractHoughLine(line):
    for rho,theta in l:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))
    return (x0, y0, x1, y1, x2, y2)

In [4]:
plt.figsize(28,28)
additional = 0
fig, axis = plt.subplots(1, len(thresholds) + additional)
# axis[0].imshow(img)
# axis[1].imshow(gray, cmap=cm.gist_gray)
for ax,bi in zip(axis[additional:], map(lambda t: cv2.threshold(gray, 150, 150, t), thresholds)):
    i = bi[1]
    edges = cv2.Canny(i,50,150,apertureSize = 3)
    lines = cv2.HoughLines(edges,1,np.pi/270,255)
    colorimage = cv2.cvtColor(i, cv2.COLOR_GRAY2BGR)
    for l in lines:
        (x0, y0, x1, y1, x2, y2) = extractHoughLine(l)
        cv2.line(colorimage,(x1,y1),(x2,y2),(255,0,0),2)
    ax.imshow(edges, cmap=cm.gist_gray)
    # ax.imshow(colorimage, cmap=cm.gist_gray)



In [5]:
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
d, thresh = cv2.threshold(gray, 150, 150, cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
crop = gray[y:y+h,x:x+w]
imshow(thresh, cmap=cm.gist_gray)


Out[5]:
<matplotlib.image.AxesImage at 0x56d46d0>

In [6]:
plt.figsize(25,25)
additional = 0
ts = [
    (0,5),
    (0,150),
    (0,200),
    (0,300),
    (0,350)
]
fig, axis = plt.subplots(1, len(ts) + additional)
d,i = cv2.threshold(gray, 150, 150, cv2.THRESH_TRUNC)
for ax, bt in zip(axis[additional:], ts):
    t1, t2 = bt
    edges = cv2.Canny(i,t1,t2,apertureSize = 3)
    lines = cv2.HoughLines(edges,1,np.pi/90,255)
    colorimage = cv2.cvtColor(i, cv2.COLOR_GRAY2BGR)
    if lines != None:
        for l in lines:
            (x0, y0, x1, y1, x2, y2) = extractHoughLine(l)
            cv2.line(colorimage,(x1,y1),(x2,y2),(255,0,0),2)
    ax.imshow(colorimage, cmap=cm.gist_gray)
    # ax.imshow(colorimage)



In [6]: