import cv2 as cv
import numpy as np
filename = 'chart164254737915328578.png'
img = cv.imread(cv.samples.findFile(filename))
cImage0 = np.copy(img) # image to draw lines
cImage = np.copy(img) # image to draw lines
cv.imshow("image", img) # name the window as "image"
# change all the black pixels to white
height, width, _ = cImage.shape
for i in range(height):
for j in range(width):
# img[i,j] is the RGB pixel at position (i, j)
# check if it's [0, 0, 0] and replace with [255, 255, 255] if so
if cImage[i, j].sum() == 0:
cImage[i, j] = [255, 255, 255]
cv.imshow("cImage", cImage)
cv.waitKey(0)
cv.destroyWindow("cImage")
gray = cv.cvtColor(cImage, cv.COLOR_BGR2GRAY)
cv.imshow("gray", gray)
cv.waitKey(0)
cv.destroyWindow("gray")
canny = cv.Canny(gray, 50, 150)
cv.imshow("canny", canny)
cv.waitKey(0)
cv.destroyWindow("canny")
# cv.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) → lines
rho = 1
theta = np.pi / 180
threshold = 5
minLinLength = 1
maxLineGap = 1
linesP = cv.HoughLinesP(canny, rho, theta, threshold, None, minLinLength, maxLineGap)
def is_vertical(line):
return line[0] == line[2]
def is_horizontal(line):
return line[1] == line[3]
horizontal_lines = []
vertical_lines = []
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
if (is_vertical(l)):
vertical_lines.append(l)
elif (is_horizontal(l)):
horizontal_lines.append(l)
min = height
max = 0
for i, line in enumerate(horizontal_lines):
if line[1] < min:
min = line[1]
if line[1] > max:
max = line[1]
print(min)
print(max)
for i, line in enumerate(horizontal_lines):
#cv.line(cImage0, (line[0], line[1]), (line[2], line[3]), (0, 255, 0), 3, cv.LINE_AA)
cv.putText(cImage0, str(round((max - line[1]) / (max - min) * 100, 1)), (line[0], line[1] + 10),
cv.FONT_HERSHEY_PLAIN, 0.8, (0, 0, 0), 2, 8, 0)
# for i, line in enumerate(vertical_lines):
# cv.line(cImage, (line[0], line[1]), (line[2], line[3]), (0, 0, 255), 3, cv.LINE_AA)
cv.imshow("with_line", cImage0)
cv.waitKey(0)
cv.destroyWindow("with_line") # close the window
cv.waitKey(0)
cv.destroyWindow("image") # close the window