Created
November 16, 2018 09:45
-
-
Save shrestharikesh/3e7258fecd20577787c516ec5279466c to your computer and use it in GitHub Desktop.
vehicle character segmentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import math | |
import matplotlib.pyplot as plt | |
## (1) read | |
img = cv2.imread("img.jpg") | |
image = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21) | |
cv2.imshow("denoised", img) | |
cv2.waitKey(0) | |
H = 100. | |
height, width, depth = image.shape | |
imgScale = H/height | |
newX,newY = image.shape[1]*imgScale, image.shape[0]*imgScale | |
img = cv2.resize(image,(int(newX),int(newY))) | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
## (2) threshold | |
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) | |
cv2.imshow("threshed", threshed) | |
cv2.waitKey(0) | |
# horizontal segmentation | |
hist = cv2.reduce(threshed,1, cv2.REDUCE_AVG).reshape(-1) | |
print(hist) | |
th = 10 | |
H,W = threshed.shape[:2] | |
uppers = [y for y in range(H-1) if hist[y]<=th and hist[y+1]>th] | |
lowers = [y for y in range(H-1) if hist[y]>th and hist[y+1]<=th] | |
print(uppers) | |
print(lowers) | |
if(uppers[0]>lowers[0]): | |
del uppers[0] | |
del lowers[len(lowers)-1] | |
images = [] | |
for q in range(0,len(uppers)): | |
a= uppers[q] | |
b= lowers[q] | |
images.append(threshed[a:b,0:(W-1)]) | |
#vertical segmentation | |
# segmentation of characters | |
segments=[] | |
for p in range(0,len(images)): | |
hist = cv2.reduce(images[p],0, cv2.REDUCE_AVG).reshape(-1) | |
uppers = [x for x in range(W-1) if hist[x]<=th and hist[x+1]>th] | |
lowers = [x for x in range(W-1) if hist[x]>th and hist[x+1]<=th] | |
rotated = cv2.cvtColor(images[p], cv2.COLOR_GRAY2BGR) | |
print("here") | |
#segment each characters | |
for q in range(0,len(uppers)): | |
H,W = images[p].shape[:2] | |
if(H>10): | |
a= uppers[q] | |
b=lowers[q] | |
segments.append(images[p][0:H,a:b]) | |
print("here") | |
print(len(segments)) | |
for i in range(0,len(segments)): | |
cv2.imwrite('segments',segments[i]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment