coding utf-8 In import cv2 get_ipython magic pylab inline In image cv2

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
# coding: utf-8
# In[1]:
import cv2
get_ipython().magic(u'pylab inline')
# In[2]:
image = cv2.imread("iphbaCy0p.jpg")
# In[3]:
grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, grey_thresh = cv2.threshold(grey, 55, 255, cv2.THRESH_BINARY)
figure(figsize=(16, 12))
imshow(grey_thresh, cmap=cm.gray)
# In[4]:
#th3 = cv2.adaptiveThreshold(grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
# cv2.THRESH_BINARY,11,2)
kernel = np.ones((10,10), np.uint8)
text_dilated = cv2.dilate(grey_thresh, kernel)
figure(figsize=(16, 12))
imshow(text_dilated, cmap=cm.gray)
# In[5]:
contours, _ = cv2.findContours(text_dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
def good_contour(c):
x,y,w,h = cv2.boundingRect(c)
return 15 < w < 1000 and 15 < h < 30
contours = [cv2.convexHull(c) for c in contours if good_contour(c)]
text_mask = np.zeros(grey.shape, dtype=np.uint8)
#cv2.drawContours(text_mask, contours, -1, [255], 3)
rectangles = []
for c in contours:
rectangles.append(cv2.boundingRect(c))
for x,y,w,h in rectangles:
cv2.rectangle(text_mask, (x, y), (x+w,y+h), 255, cv2.cv.CV_FILLED)
figure(figsize=(16, 12))
imshow(text_mask, cmap=cm.gray)
# In[6]:
print text_mask.dtype
text_only = cv2.bitwise_and(grey_thresh, grey_thresh, mask=text_mask)
figure(figsize=(16, 12))
imshow(text_only, cmap=cm.gray)
# In[7]:
rect = rectangles[10]
x,y,w,h = rect
patch = grey_thresh[y:y+h, x:x+w]
imshow(patch, cmap=cm.gray)
# In[9]:
char_contours, _ = cv2.findContours(patch.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
patch2 = patch.copy()
for c in char_contours:
c = cv2.convexHull(c)
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(patch2, (x,y), (x+w, y+h), 128)
imshow(patch2, cmap=cm.gray)
# In[21]:
import os.path
output_dir = "images"
i = 0
for r in rectangles:
x,y,w,h = r
patch = grey_thresh[y:y+h, x:x+w]
char_contours, hierarchy = cv2.findContours(patch.copy(), cv2.cv.CV_RETR_EXTERNAL ,cv2.CHAIN_APPROX_SIMPLE)
#print len(char_contours)
q += len(char_contours)
patch2 = patch.copy()
for j, c in enumerate(char_contours):
#print hierarchy[j]
#if hierarchy[j][1] < 0:
# continue
c = cv2.convexHull(c)
x,y,w,h = cv2.boundingRect(c)
#cv2.rectangle(patch2, (x,y), (x+w, y+h), 128)
imsave(os.path.join(output_dir, "%d.png" % i), patch2[y:y+h, x:x+w], cmap=cm.gray)
i += 1