9.传统的轨道画线算法()

发布时间:2023年12月27日

轨道画线分为以下步骤:

1.读取摄像头图片

2.图片灰度处理,截取轨道区域的图片

3.中值滤波处理,并区域取均值后做期望差的绝对值。本人通过一些轨道图片实验,用这种方法二值化得到的效果比caany算子等方法的效果好

4.二值化后再用DBSAN聚类算法对图片分类

5.对分好类的坐标在图片中画图

具体代码如下:

import numpy as np
import cv2


colors = [ (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),
                            (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128),
                            (64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128),
                            (128, 64, 12)]

def cluster(points, radius=100):
    """
    points: pointcloud
    radius: max cluster range
    """
    print("................", len(points))
    items = []
    while len(points)>1:
        item = np.array([points[0]])
        base = points[0]
        points = np.delete(points, 0, 0)
        distance = (points[:,0]-base[0])**2+(points[:,1]-base[1])**2#获得距离
        infected_points = np.where(distance <= radius**2)#与base距离小于radius**2的点的坐标
        item = np.append(item, points[infected_points], axis=0)
        border_points = points[infected_points]
        points = np.delete(points, infected_points, 0)
        #print("................",len(points))
        #print(border_points)
        while len(border_points) > 0:
            border_base = border_points[0]
            border_points = np.delete(border_points, 0, 0)
            border_distance = (points[:,0]-border_base[0])**2+(points[:,1]-border_base[1])**2
            border_infected_points = np.where(border_distance <= radius**2)
            #print("/",border_infected_points)
            item = np.append(item, points[border_infected_points], axis=0)
            for k in border_infected_points:
                if points[k] not in border_points:
                    border_points=np.append(border_points,points[k], axis=0)
            #border_points = points[border_infected_points]
            points = np.delete(points, border_infected_points, 0)
        items.append(item)
    return items



#2.图像的灰度处理、边缘分割
def mean_img(img):
    # gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #1.图片的灰度,截取处理
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imgss=img[540:743, 810:1035]
    gray_img = gray_img[540:741, 810:1030]#[540:741, 810:1080]
    img2=gray_img
    print(img2.mean())

    #中值滤波
    gray_img = cv2.medianBlur(gray_img, ksize=3)
    cv2.imshow("Dilated Image", gray_img)
    cv2.waitKey(0)

    #2.行做期望差,3个值取均值再做差
    for i in range(gray_img.shape[0]):
        for j in range(gray_img.shape[1]-2):
            ss1=gray_img[i, j:j+2].mean()
            m=abs(gray_img[i][j]-ss1)
            if m>13:
                img2[i][j] =255
            else:
                img2[i][j] =0

    img2[:,-3:]=0
    cv2.imshow("img_mean", img2)
    cv2.waitKey(0)

    # 3.腐蚀膨胀消除轨道线外的点
    kernel = np.uint8(np.ones((5, 2)))
    # 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方
    dilated = cv2.dilate(img2, kernel)
    #显示膨胀后的图像
    #dilated[:, -6:] = 0
    cv2.imshow("Dilated Image", dilated)
    cv2.waitKey(0)
    ss=np.argwhere(dilated>0)
    print(ss)

    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\120.jpg",dilated)

    #聚类算法
    items = cluster(ss, radius=5)
    print(len(items))
    i=0
    for item in items:
        print("====>", len(item))
        if len(item)>500:
            for k in item:
                imgss[k[0]][k[1]]=colors[i]
            i+=1
    cv2.imshow("ss",imgss)
    cv2.waitKey(0)
    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\121.jpg", imgss)

    return ss




#3.画图
def draw_line(items):
    print(123)


if __name__ == '__main__':

    img_path=r"D:\AI\project\eye_hand_biaoding\railways\img\1.jpg"

    img=cv2.imread(img_path)

    ss=mean_img(img)

    ss=np.array(ss)

    items=cluster(ss, radius=25)

通过以上聚类的方法处理后的图片如下:

? ? ? ? 接下来对两类点进行处理。在这里目前想到的处理方式有两种:一是:首先对每个类取行的中值或者均值,即每个类的每行只保留一个坐标(均值或者中间值),去除掉了每行两边的坐标。但这个效果不太好,后面会附加代码和处理的图片结果;二是根据霍夫曼求直线的方法,自己重新写个获取直线。

一、取均值或者中值的代码如下:

import numpy as np
import cv2
from sklearn.linear_model import LinearRegression
import time




#https://blog.csdn.net/L888666Q/article/details/127209464
#霍夫曼取直线原理:https://blog.csdn.net/fengjiexyb/article/details/78075888

colors = [ (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),
                            (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128),
                            (64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128),
                            (128, 64, 12)]

def cluster(points, radius=100):
    """
    points: pointcloud
    radius: max cluster range
    """
    print("................", len(points))
    items = []
    while len(points)>1:
        item = np.array([points[0]])
        base = points[0]
        points = np.delete(points, 0, 0)
        distance = (points[:,0]-base[0])**2+(points[:,1]-base[1])**2#获得距离
        infected_points = np.where(distance <= radius**2)#与base距离小于radius**2的点的坐标
        item = np.append(item, points[infected_points], axis=0)
        border_points = points[infected_points]
        points = np.delete(points, infected_points, 0)
        #print("................",len(points))
        #print(border_points)
        while len(border_points) > 0:
            border_base = border_points[0]
            border_points = np.delete(border_points, 0, 0)
            border_distance = (points[:,0]-border_base[0])**2+(points[:,1]-border_base[1])**2
            border_infected_points = np.where(border_distance <= radius**2)
            #print("/",border_infected_points)
            item = np.append(item, points[border_infected_points], axis=0)
            if len(border_infected_points)>0:
                for k in border_infected_points:
                    if points[k] not in border_points:
                        border_points=np.append(border_points,points[k], axis=0)
                #border_points = points[border_infected_points]
            points = np.delete(points, border_infected_points, 0)
        items.append(item)
    return items


def k_mean(out):
    print("........................开始计算图片的均值.....................")
    median = {}
    i = 1
    for items in out:
        median[str(i)] = []
        result = items[:, :-1]
        ss = result.shape
        result = result.reshape(ss[1], ss[0])
        result = result[0].tolist()
        result = list(set(result))  # 去掉result重复的值
        for m in result:
            #print("...............", m, "...............................")
            item = np.where(items[:, :-1] == m)[0]
            # median[str(i)].append(items[item[len(item)//2]].tolist()) #中位数,有用
            median[str(i)].append([m, int(items[item][:, -1:].mean())])  # 均值
        i += 1
    return median

#直线的拟合
def lines(median,distances):
    print("...................直线的拟合......................")
    for items in median:
        n_m=np.array(median[items])#转换为array数据
        means=n_m[:,1:]#取坐标的第二列
        lens=n_m[-1][0]+1#总共多少个坐标,即坐标个数
        #print(lens)

        #1.获取x1,x2的坐标
        if lens%4>2:
            x10=lens//4+1
        else:
            x10 = lens // 4
        x20=x10*3
        x=lens//2
        #print("x1,x2:  ",x10,x20)

        #2.获取y1,y2的坐标
        y10=means[:lens//2].mean()
        y20 = means[lens // 2-1:].mean()
        y=means.mean()
        #print("y1,y2:  ", y10, y20)

        #3.获取直线斜率k k=(y1-y2)/(x1-x2)
        k=(y10-y20)/(x10-x20)
        #print("k:  ",k)
        #print("x,y:      ",x,y)

        #4.预测某个点的y值 y-pred=k*(x_pred-x)+y  n_m[i]
        for i in range(len(n_m)):
            y_pred = k * (n_m[i][0] - x) + y
            #print("===>",y_pred,n_m[i][0],n_m[i][1])
            if abs(y_pred-n_m[i][1])>distances:
                n_m[i][1]=y_pred
                #median[items][i][1]=int(y_pred)
        median[items]=n_m.tolist()
    return median



#2.图像的灰度处理、边缘分割
def mean_img(img,x1,x2,y1,y2):

    imgs=img.copy()
    img4 = img.copy()
    #1.图片的灰度,截取处理
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_img = gray_img[x1:x2, y1:y2]#[540:741, 810:1080],截取轨道画线的区域,对该区域识别轨道
    img2=gray_img

    #2.中值滤波
    gray_img = cv2.medianBlur(gray_img, ksize=3)
    # cv2.imshow("Dilated Image", gray_img)
    # cv2.waitKey(0)
    st=time.time()
    for i in range(gray_img.shape[0]):
        for j in range(gray_img.shape[1]-2):
            ss1 = gray_img[i, j:j + 2].mean()
            m=abs(gray_img[i][j]-ss1)
            if m>9:
                img2[i][j] =255
            else:
                img2[i][j] =0
    img2[:,-3:]=0

    et = time.time()
    print("kmeans时间",et-st)

    # cv2.imshow("img_mean", img2)
    # cv2.waitKey(0)

    # 3.腐蚀膨胀消除轨道线外的点
    st1=time.time()
    kernel = np.uint8(np.ones((2, 1)))
    # 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方
    dilated = cv2.dilate(img2, kernel)
    #显示膨胀后的图像
    # cv2.imshow("Dilated Image", dilated)
    # cv2.waitKey(0)
    kernel = np.ones((2, 2), np.uint8)
    dilated = cv2.erode(dilated, kernel)
    cv2.imshow("ss",dilated)
    cv2.waitKey(0)

    ss=np.argwhere(img2>0)#dilated
    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\120.jpg",dilated)
    #聚类算法
    items = cluster(ss, radius=3)
    print(len(items))
    i=0
    out=[]#获得大于300个坐标的类
    for item in items:
        if len(item)>300:
            out.append(item)
            print("====>", len(item))
            for k in item:
                img[k[0]+x1][k[1]+y1]=colors[i]#[540:743, 810:1035]
            i+=1
    # cv2.imshow("ss",img)
    # cv2.waitKey(0)
    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\121.jpg", img)
    et1 = time.time()
    print("聚类时间:", et1 - st1)

    #求聚类的每类每行的中位数
    median=k_mean(out)

    #根据中位数画图
    j=0
    for item in median:
        for k in median[item]:
            #print(k[0],k[1])
            imgs[k[0]+x1][k[1]+y1] = colors[j]  # [540:743, 810:1035]
        j+=1
    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\122.jpg", imgs)

    et3=time.time()
    print("中位数时间:", et3 - et1)
    print(".....................................","\n")
    #用直线拟合,首先用两个均值得到初始线的斜率及均值坐标,然后不断对远离的坐标点拟合

    distances=4
    while distances>0:
        median=lines(median,distances)
        distances-=1

    #画图
    j = 0
    for item in median:
        for k in median[item]:
            # print(k[0],k[1])
            img4[k[0] + x1][k[1] + y1] = colors[j]  # [540:743, 810:1035]
        j += 1
    cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\img\\123.jpg", img4)

    et4=time.time()
    print("直线拟合消耗时间:",et4-et3)


    return out

if __name__ == '__main__':

    start=time.time()

    img_path=r图片路径"

    img=cv2.imread(img_path)

    out=mean_img(img,x1=650,x2=741,y1=825,y2=1025)#x1=540,x2=741,y1=810,y2=1030

    end=time.time()

    print("time:",end-start)








????????上述的直线拟合没有用最小二乘法,处理后的画图结果如下:

显然,拟合的结果并不好。下面用霍夫曼求直线的方法拟合。

二、霍夫曼圆找直线

文章来源:https://blog.csdn.net/weixin_71719718/article/details/135199000
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。