from skimage.io import imread
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
#get image and convert it to grayscale
sample1 = 'https://cdn.instructables.com/F92/1G4I/IJX58MRB/F921G4IIJX58MRB.LARGE.jpg?auto=webp&width=350'
sample2 = "https://cdn.instructables.com/F92/1G4I/IJX58MRB/F921G4IIJX58MRB.LARGE.jpg"
sample3 = "https://docparser.com/blog/wp-content/uploads/2017/11/ocr-accuracy-1-1024x285.png"
sample4 = "https://i.stack.imgur.com/sxRq9.jpg"
sample5 = "https://media-cdn.tripadvisor.com/media/photo-s/04/d0/50/1d/del-frisco-s.jpg"
sample6 = "resources/malay.png"
img = rgb2gray(imread(sample6))
plt.imshow(img, cmap="gray")
<matplotlib.image.AxesImage at 0x7f400aab6a10>
from skimage.filters import sobel
from skimage.util import invert
sobel_image = invert(sobel(img))
plt.imshow(sobel_image)
<matplotlib.image.AxesImage at 0x7f400a9e5ed0>
import numpy as np
from skimage.transform import rotate
#find the horizontal projection of all the rows in the image
#rotate the image between angles -10 to 10 degrees and find the angle which gives the least median of horizontal projection
def horizontal_projections(sobel_image):
sum_of_cols = []
rows,cols = sobel_image.shape
for row in range(rows-1):
sum_of_cols.append(np.sum(sobel_image[row,:]))
return sum_of_cols
fig, ax = plt.subplots(nrows=20, figsize=(20,50))
for index,angle in enumerate(range(-10,10)):
ax[index].set_title('angle:'+str(angle))
hp = horizontal_projections(rotate(sobel_image, angle, cval=1))
xv = []
yv = []
for i, y in enumerate(hp):
xv.append(i)
yv.append(y)
ax[index].plot(yv)
fig, ax = plt.subplots(nrows=20, figsize=(10,50))
for index,angle in enumerate(range(-10,10)):
hp = horizontal_projections(rotate(sobel_image, angle, cval=1))
xv = []
yv = []
for i, y in enumerate(hp):
xv.append(i)
yv.append(y)
ax[index].set_title('angle:'+str(angle)+', median:'+str(np.median(hp)))
ax[index].boxplot(yv)
rows,cols = sobel_image.shape
predicted_angle = 0
highest_hp = 0
for index,angle in enumerate(range(-10,10)):
hp = horizontal_projections(rotate(sobel_image, angle, cval=1))
median_hp = np.median(hp)
if highest_hp < median_hp:
predicted_angle = angle
highest_hp = median_hp
fig, ax = plt.subplots(ncols=2, figsize=(20,10))
ax[0].set_title('original image grayscale')
ax[0].imshow(img, cmap="gray")
ax[1].set_title('original image rotated by angle'+str(predicted_angle))
ax[1].imshow(rotate(img, predicted_angle, cval=1), cmap="gray")
<matplotlib.image.AxesImage at 0x7f4003d3dc90>