opencv——实现智能小车巡线

代码如下:

import cv2
import numpy as np

screen_height = 480
screen_width = 640

def readImg(path):
    img = cv2.imread(path, 1)
    img = cv2.resize(img, (screen_width, screen_height))
    return img


def createWait():
    img = np.ones((screen_height, screen_width), dtype=np.uint8)
    img[:, :] = 225
    return img

def calculate(dst2):
    points = []
    sum_x = 0
    sum_y = 0
    for y in range(screen_height):
        for x in range(screen_width):
            if dst2[y][x] == 0:
                points.append([x, y])
    for point in points:
        sum_x += point[0]
        sum_y += point[1]
    points_len = len(points)
    average_x = sum_x / points_len
    average_y = sum_y / points_len

    sum_up = 0
    sum_down = 0
    for point in points:
        sum_up += point[0] * point[1]
        sum_down += point[0] ** 2
    sum_up -= points_len * average_x * average_y
    sum_down -= points_len * average_x ** 2
    b = sum_up / sum_down
    a = average_y - b * average_x
    end = {'b': b, 'a': a}

    return end

def getLine(path):
    frame = readImg(path)
    # 灰度化
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('./gray.jpg', gray)


    # 二值化
    threshold_image = cv2.threshold(gray, 60, 225, cv2.THRESH_BINARY)
    binary = threshold_image[1]
    cv2.imwrite('./binary.jpg', binary)


    # 取反
    subtract = cv2.subtract(createWait(), binary)
    cv2.imwrite('./dst2.jpg', subtract)

    # 腐蚀
    kernel = np.ones((5, 5), np.uint8)
    erode = cv2.erode(subtract, kernel, iterations=3)

    # 膨胀
    dilate = cv2.dilate(erode, kernel)

    # 寻找轮廓
    contours = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    contour = contours[0]

    area = []

    for k in range(len(contour)):
        area.append((cv2.contourArea(contour[k])))

    max_idx = np.argmax(np.array(area))

    tatImg = cv2.drawContours(createWait(), contour, max_idx, (0, 0, 225), -1)
    cv2.imwrite('./tatImg.jpg', tatImg)

    return calculate(tatImg)


def showResult(path):
    img = readImg(path)
    end = getLine(path)

    for i in range(screen_width):
        cv2.circle(img,
                   (int(i), int(end['b'] * i + end['a'])),
                   2,
                   (0, 0, 225),
                   0,
                   1)
    cv2.imshow(path[6:], img)
    cv2.imwrite('./img.jpg', img)


if __name__ == '__main__':
    path = r'path/to/your/img'
    showResult(path=path)

识别效果:

a)原图
在这里插入图片描述
b)轨迹轮廓
在这里插入图片描述

c)边缘检测
在这里插入图片描述
d)轨迹绘制
在这里插入图片描述

  • 4
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值