In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import cv2
In [ ]:
def angle_cos(p0, p1, p2):
d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
img = cv2.imread('test.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# img = cv2.GaussianBlur(img, (3, 3), 0)
# img = cv2.Canny(img, 0, 50, apertureSize=3)
# img = cv2.dilate(img, None)
# img = cv2.erode(img, np.ones((1,1)))
retval, thresh = cv2.threshold(img, 10, 100, cv2.THRESH_TRIANGLE)
bin, contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea, reverse = True)#[:100]
squares = []
for cnt in contours:
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.09*cnt_len, True)
if ((len(cnt) == 4) and
(cv2.contourArea(cnt) > 1000) and
# (cv2.contourArea(cnt) < 50000) and
cv2.isContourConvex(cnt) ):
cnt = cnt.reshape(-1, 2)
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] )
for i in range(4)])
if max_cos < 0.1:
squares.append(cnt)
bin = cv2.cvtColor(bin, cv2.COLOR_GRAY2BGR)
cv2.drawContours( bin, contours,
-1, (0, 0, 255), 1 )
items = [
img,
thresh,
bin
]
fig, axes = plt.subplots(len(items),1, figsize=(len(items)*3,12))
for ax,im in zip(axes.flatten(), items):
plt.sca(ax)
plt.imshow(im, interpolation='nearest', cmap=plt.cm.gray)
In [ ]:
img = cv2.imread('test.jpg')
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,0,255,apertureSize = 3)
gray = cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)
minLineLength = 1
maxLineGap = 1
lines = cv2.HoughLinesP(edges,3,np.pi/180,100,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
cv2.line(gray,(x1,y1),(x2,y2),(0,255,0),2)
# lines = cv2.HoughLines(edges,1,np.pi/180,200)
# for rho,theta in lines[0]:
# 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))
# cv2.line(img,(x1,y1),(x2,y2),(255,0,0),6)
items = [
img,
gray,
edges
]
fig, axes = plt.subplots(len(items),1, figsize=(12, len(items)*6))
for ax,im in zip(axes.flatten(), items):
plt.sca(ax)
plt.imshow(im, interpolation='nearest', cmap=plt.cm.gray)
In [ ]: