使用Python OpenCV给柱状图添加数值

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值