Amazing-Python-Scripts
101 строка · 2.9 Кб
1'''
2output : word detection on document (Simple OCR type of application)
3'''
4
5import cv2
6import numpy as np
7import imutils
8
9# frame read
10frame = cv2.imread('test.jpeg')
11
12# resize
13frame = cv2.resize(frame, (600, 600))
14
15# grayscale
16gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
17
18# remove noise
19blur = cv2.GaussianBlur(gray, (5, 5), 0)
20
21# otsu thresh (bimodel thresold)
22thresh = cv2.threshold(blur, 0, 255,
23cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
24
25# get structuring element
26
27horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))
28vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 25))
29print('horizontal kernel : {}'.format(horizontal_kernel))
30print('vertical kernel : {}'.format(vertical_kernel))
31
32# opening (erosion followed by dilation)
33
34horizontal_lines = cv2.morphologyEx(thresh,
35cv2.MORPH_OPEN,
36horizontal_kernel,
37iterations=2)
38vertical_lines = cv2.morphologyEx(thresh,
39cv2.MORPH_OPEN,
40vertical_kernel,
41iterations=2)
42
43# contours apply on detected lines
44# First one is source image, second is contour retrieval mode, third is contour approximation method
45
46cnts = cv2.findContours(horizontal_lines, cv2.RETR_EXTERNAL,
47cv2.CHAIN_APPROX_SIMPLE)
48cntsv = cv2.findContours(vertical_lines, cv2.RETR_EXTERNAL,
49cv2.CHAIN_APPROX_SIMPLE)
50
51# find contours
52cnts = cnts[0] if len(cnts) == 2 else cnts[1]
53cntsv = cntsv[0] if len(cntsv) == 2 else cntsv[1]
54
55for c in cnts:
56cv2.drawContours(frame, [c], -1, (255, 255, 255), 2)
57for c in cntsv:
58cv2.drawContours(frame, [c], -1, (255, 255, 255), 2)
59
60# imshow
61cv2.imshow('thresh', thresh)
62cv2.imshow('horizontal_lines', horizontal_lines)
63cv2.imshow('vertical_lines', vertical_lines)
64cv2.imshow('frame', frame)
65
66# grayscale
67
68gray1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
69thresh1 = cv2.adaptiveThreshold(gray1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
70cv2.THRESH_BINARY, 23, 30)
71canny = imutils.auto_canny(thresh1)
72
73output = cv2.bitwise_not(canny)
74kernel = np.ones((5, 5), np.uint8)
75
76opening = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)
77
78dilation = cv2.dilate(canny, kernel, iterations=1)
79
80contour, hierachy = cv2.findContours(dilation, cv2.RETR_TREE,
81cv2.CHAIN_APPROX_SIMPLE)
82
83for i in contour:
84area = cv2.contourArea(i)
85if area > 20:
86x, y, w, h = cv2.boundingRect(i)
87cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 120, 255), 2)
88
89cv2.imshow('output', output)
90cv2.imshow('dilate', dilation)
91cv2.imshow('opening', opening)
92cv2.imshow('original_frame', frame)
93cv2.imshow('canny', canny)
94cv2.imshow('thresh1', thresh1)
95
96# Saving output image
97cv2.imwrite('output.jpg', frame)
98
99# destroy all window
100cv2.waitKey(0)
101cv2.destroyAllWindows()
102