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

轨道画线分为以下步骤:

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)

    #聚类算法
    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)

    return ss


if __name__ == '__main__':

    img_path=r"图片路径"

    img=cv2.imread(img_path)

    ss=mean_img(img)

    ss=np.array(ss)

    items=cluster(ss, radius=25)

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

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

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

import numpy as np
import cv2
import time


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
    #聚类算法
    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)
    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

    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

    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)

    end=time.time()

    print("time:",end-start)

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

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

二、霍夫曼圆找直线

        这种方法不用上面的代码,简单直接,并且效果更好。代码和结果如下:

代码:

import numpy as np
import time
import cv2

#2.图片处理,再通过上面的聚类函数获取轨道的类
def mean_img(img,x1,x2,y1,y2):

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


    #2.霍夫曼直线求点
    edges=cv2.Canny(gray_img, 120, 255, apertureSize=3)
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 30, minLineLength=50, maxLineGap=10)

    ss=[]#获取每条直线的长度的平方,以便后面根据直线的长度排序
    for line in lines:
        #   print(type(line))
        x10, y10, x20, y20 = line[0]
        distance=(y20-y10)**2+(x10-x20)**2#每条直线长度的平方
        ss.append([distance,[x10, y10, x20, y20]])
    ss=np.array(ss)

    indexs=np.lexsort([ss[:,0]])#根据长度对直线由小到大排序,获得排序的index值
    data=ss[indexs,:]#data:排序后的ss

    lines=data[:,-1:]
    index_2 =[]#从lines获取轨道两边的直线
    index_2.append(lines[-1][0])#首先获取长度最长的一条直线
    for i in range(len(lines)-1,0,-1):
        if abs(lines[i][0][0]-index_2[0][0])>25:#另一条直线的获取是从后向前遍历,两直线一端的横坐标的差大于25时,则是另外一条直线,获得后结束后面的遍历
            index_2.append(lines[i][0])
            break
    #画图
    for iten in index_2:
        x10, y10, x20, y20 = iten
        cv2.line(img, (x10 + y1, y10 + x1), (x20 + y1, y20 + x1), (0, 0, 255), 2)
    cv2.imwrite("保存文件的路径\\120.jpg", img)
    # cv2.imshow("line_detect_possible_demo", img)
    # cv2.waitKey(0)


if __name__ == '__main__':

    start=time.time()

    img_path=r"图片路径"

    img=cv2.imread(img_path)
    #x1, x2, y1, y2:表示在相机图片中截取要画线区域的轨道部分的区域(减小计算,使背景更简单)
    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)

效果如下:

        当然,这个是近焦相机拍的近距离的轨道,可以再用远焦相机拍远距离的轨道拟合直线,然后将两条直线融合。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/273741.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

普中STM32-PZ6806L开发板(HAL库函数实现-批量操作GPIO引脚实现跑马灯)

简介 实现跑马灯, 但一个个引脚的操作实在是有些繁琐, 本次使用GPIO_WritePin接口实现批量操作GPIO引脚实现LED跑马灯。电路原理图 LED灯电路 LED灯连接主控芯片引脚图 实现说明 stm32f1xx_hal_gpio.h 关于GPIO引脚的定义如下 /** defgroup GPIO_pins_define GPIO pins …

[Angular] 笔记 13:模板驱动表单 - 单选按钮

Radio Buttons (Template Driven Forms) Radio Button&#xff0c; input 元素类型全部为 radio&#xff0c;因为是单选&#xff0c;name 属性值必须相同。 pokemon-template-form.component.html: <form #form"ngForm">Pokemon Name:<input type"t…

2D transform 1-translate

移位&#xff1a;translate 缩放&#xff1a;scale 旋转&#xff1a;rotate 扭曲&#xff1a;skew <style>.outer {width: 200px;height: 200px;border: 2px solid black;margin-top: 100px;}.inner {width: 200px;height: 200px;background-color: pink;transform: t…

使用web_video_server进行网页段的视频传输

引言&#xff1a;在项目中&#xff0c;需要实现无人机摄像头采集到的图像回传到window下进行查看&#xff0c;为此&#xff0c;选择使用web_video_server功能包实现局域网下的图像传输 硬件环境&#xff1a; 硬件&#xff1a;Jetson orin nano 8G D435摄像头 环境&#xff…

vue3+elementPlus+cascader动态加载封装自定义组件+v-model指令实现父子通信

文章目录 select普通操作 &#xff08;1&#xff09;cascader操作&#xff08;2&#xff09; select普通操作 &#xff08;1&#xff09; 搜索条件需求&#xff1a;接口入参需要houseId&#xff0c;但是要先选择完楼栋&#xff0c;再选择单元&#xff0c;最后选择房屋 如图&a…

k8s的二进制部署(一)

k8s的二进制部署&#xff1a;源码包部署 环境&#xff1a; k8smaster01: 20.0.0.71 kube-apiserver kube-controller-manager kube-schedule ETCD k8smaster02: 20.0.0.72 kube-apiserver kube-controller-manager kube-schedule Node节点01: 20.0.0.73 kubelet kube-pr…

GrayLog日志平台的基本使用-ssh接入Dashboards展示

这里使用的版本为graylog4.2.10 1、一键安装graylog4.2.10&#xff0c;解压zip包&#xff0c;执行脚本就行 链接&#xff1a;https://pan.baidu.com/s/11U7GpBZ1B7PXR8pyWVcHNw?pwdudln 提取码&#xff1a;udln 2、通过rsyslog采集系统日志&#xff0c;具体操作参考前面文…

饮用水中的砷、硝酸盐含量超标,离子交换工艺分享

随着人们对健康和生活质量的日益关注&#xff0c;饮用水安全问题成为了社会关注的焦点。在自然水体中的含量往往较高&#xff0c;而这些物质对人体健康存在一定的潜在风险。因此&#xff0c;饮用水处理中如何有效去除溴酸盐和硝酸盐&#xff0c;成为了当前水处理行业的重要课题…

CTFshow-pwn入门-栈溢出pwn39-pwn40

pwn39 首先我们还是先将二级制文件托到虚拟机里面查看文件的保护信息。 chmod x pwn checksec pwn文件依然是只开启了栈不可执行&#xff0c;canary和pie都没开。并且该文件是32位的&#xff0c;那我们就托到ida32中反编译一下吧。 int __cdecl main(int argc, const char **…

LSTM的记忆能力实验 [HBU]

目录 模型构建 LSTM层 模型训练 多组训练 模型评价 模型在不同长度的数据集上的准确率变化图 模型汇总 总结 长短期记忆网络&#xff08;Long Short-Term Memory Network&#xff0c;LSTM&#xff09;是一种可以有效缓解长程依赖问题的循环神经网络&#xff0e;LSTM 的…

go 源码解读 - sync.Mutex

sync.Mutex mutex简介mutex 方法源码标志位获取锁LocklockSlowUnlock怎么 调度 goroutineruntime 方法 mutex简介 mutex 是 一种实现互斥的同步原语。&#xff08;go-version 1.21&#xff09; &#xff08;还涉及到Go运行时的内部机制&#xff09;mutex 方法 Lock() 方法用于…

nodejs业务分层如何写后端接口

这里展示的是在node express 项目中的操作 &#xff0c;数据库使用的是MongoDB&#xff0c;前期关于express和MongoDB的文章可访问&#xff1a; Nodejs后端express框架 server后端接口操作&#xff1a;通过路由匹配——>调用对应的 Controller——>进行 Service调用——&…

如何将语音版大模型AI接入自己的项目里(语音ChatGPT)

如何将语音版大模型AI接入自己的项目里语音ChatGPT 一、语音版大模型AI二、使用步骤1、接口2、请求参数3、请求参数示例4、接口 返回示例5、智能生成API代码 三、 如何获取appKey和uid1、申请appKey:2、获取appKey和uid 四、重要说明 一、语音版大模型AI 基于阿里通义千问、百…

ueditor富文本编辑器中图片上传地址配置以及抓取远程图片地址的配置

一&#xff1a;图片上传保存地址配置 打开文件ueditor.php,找到imagePathFormat进行修改即可 一&#xff1a;远程抓取图片配置 打开文件ueditor.config.js,找到catchRemoteImageEnable&#xff0c;取消注释即可

ElasticSearch 聚合统计

聚合统计 度量聚合&#xff1a;求字段的平均值&#xff0c;最小值&#xff0c;最大值&#xff0c;总和等 桶聚合&#xff1a;将文档分成不同的桶&#xff0c;桶的划分可以根据字段的值&#xff0c;范围&#xff0c;日期间隔 管道聚合&#xff1a;在桶聚合的结果上执行进一步计…

线程学习(3)-volatile关键字,wait/notify的使用

​ &#x1f495;"命由我作&#xff0c;福自己求"&#x1f495; 作者&#xff1a;Mylvzi 文章主要内容&#xff1a;线程学习(2)​​​​ 一.volatile关键字 volatile关键字是多线程编程中一个非常重要的概念&#xff0c;它主要有两个功能&#xff1a;保证内存可见性…

JVM GC 算法原理概述

对于JVM的垃圾收集&#xff08;GC&#xff09;&#xff0c;这是一个作为Java开发者必须了解的内容&#xff0c;那么&#xff0c;我们需要去了解哪些内容呢&#xff0c;其实&#xff0c;GC主要是解决下面的三个问题&#xff1a; 哪些内存需要回收&#xff1f; 什么时候回收&…

Pandas教程(二)—— 不同格式的数据读取

前言&#xff1a;几种常用数据格式的介绍 csv文件 1. 逗号分隔值文件&#xff0c;以纯文本形式&#xff08;记事本&#xff09;存储表格数据 2. 它是一种平面文件&#xff1a;即只存储数据和文字&#xff0c;不能存储公式、图表等 3. 更适合存储大数据&#xff0c;一般用来批…

GitLab 删除或移动项目

首先明说&#xff0c;删除后无法恢复 第一步&#xff1a;找到要删除的项目 第二步&#xff1a;进入目录后&#xff0c;左侧菜单&#xff0c;设置 >>> 通用&#xff0c;拉到最下面找到“高级”&#xff0c;点击右侧“展开” 第三步&#xff1a;点击“展开”后往下拉&a…

作业--day37

课上strcut的练习改成class&#xff0c;并写一个有默认参数的函数&#xff0c;把声明和定义分开&#xff0c;并在主函数内成功调用 #include <iostream> #include <iomanip> #include <cstring>using namespace std;class stu{ private:int age;char sex;fl…
最新文章