识别图片中曲线并获取其坐标
github主页:https://github.com/Taot-chen
有时候需要用到一些数据库里面曲线图的数据,进行进一步的变换处理,但是很多时候都只有图片,没有数据。基于这个问题,给出了以下算法。
思路:
1)通过图像算法中常用的边界识别的方法来识别曲线;
2)根据曲线上每一点的像素坐标和坐标轴的数值范围,来计算曲线上每一个像素点在坐标轴中的像素坐标。
实现过程:
一、曲线识别
1)图片预处理
思路:
将待处理的图像转换成灰度图,在转换成二值图像;対二值图像的每一行和每一列的像素求和,根据像素和识别出图像的坐标轴范围;在坐标轴范围内遍历二值图像的每一列,将每列中像素值为0的像素下面的像素值全部置零。
原图:
[(img-PlRNIiCW-1636440564958)(“图片路径”, “原图”)]
具体实现:
将图像转换成二值图像:
# 打开图片
img = cv.imread(pic_name)
# 灰度化
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 二值化
# 此时的第二个和第三个参数,
# 即二值化的上下阈值需要根据图片的实际情况个来调整
ret, binary_img = cv.threshold(gray_img, 180, 255, cv.THRESH_BINARY)
识别坐标轴的范围:
# 图像像素按行和列求和
# 二值图像反相
con_bi_img = 255 - binary_img
column_sum_img = np.sum(con_bi_img, axis=0)
row_sum_img = np.sum(con_bi_img, axis=1)
# 排序
sort_column_sum = np.sort(column_sum_img)
sort_column_sum_indices = np.argsort(column_sum_img)
sort_row_sum = np.sort(row_sum_img)
sort_row_sum_indices = np.argsort(row_sum_img)
print("列:\n")
print(sort_column_sum[len(sort_column_sum) - 5:])
print(sort_column_sum_indices[len(sort_column_sum_indices) - 5:])
print("行:\n")
print(sort_row_sum[len(sort_row_sum) - 5:])
print(sort_row_sum_indices[len(sort_row_sum_indices) - 5:])
将曲线和坐标轴之间的区域设置成黑色:
for i in range(45, 773):
flag = 0
for j in range(73, 495):
if binary_img[j][i] == 0:
flag += j
break
for j in range(flag, 495):
binary_img[j][i] = 0
</