怎么从图片中提取线 python
import numpy as npimport matplotlib.pyplot as pltimport cv2import pylab as mpl# import matplotlib as mplfrom scipy.signal import savgol_filterfrom signal_process.basic_signal_pro import normalize_funa
·
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pylab as mpl # import matplotlib as mpl
from scipy.signal import savgol_filter
from signal_process.basic_signal_pro import normalize_fun
a = cv2.imread(r'.jpg')
a_red = a[:, :, 2]
def get_point_2(img):
down = cv2.pyrDown(img)
down = cv2.pyrDown(down)
thresh, pic = cv2.threshold(down, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
erode = cv2.erode(pic, kernel)
dilate = cv2.dilate(erode, kernel)
cor = np.where(dilate > 0)
print(cor)
# 图像坐标系(x,-y)转换到矩阵坐标系(row, col)
arr_col = -cor[0]
arr_row = cor[1]
# plt.scatter(arr_row, arr_col)
# 没有问题,执行下一步。观察scatter图像,发现图像较粗的原因是一个x对应多个y,那么就需要做x的删减操作
# 也就是使一个arr_row对应一个arr_col,具体选第一个出现的
# step_1: 以x坐标值做排序
arr_new = np.c_[arr_row, arr_col]
arr_sort = arr_new[np.argsort(arr_new[:, 0])]
# arr_sort = np.sort(arr_new)
# 打印一下
# print(arr_sort[:, 0][0:100]) # 结果符合预期
# step_2:同一个x对应下的y只要一个
down_x = []
down_y = []
for i in range(1, len(arr_row)):
if arr_sort[i, 0] != arr_sort[i-1, 0]:
down_x.append(arr_sort[i, 0])
down_y.append(arr_sort[i, 1])
# 画一下线,可以,但是线条不好看
# plt.plot(down_x, down_y)
# 做一个平滑处理
sav_y = savgol_filter(down_y, 15, 5)
return sav_y
# plt.plot(sav_y)
# plt.show()
原图片长这样,看看有没有搞得更好
我处理出来的
更多推荐
已为社区贡献1条内容
所有评论(0)