代码如下:
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)轨迹轮廓
文章来源:https://www.toymoban.com/news/detail-760305.html
c)边缘检测
d)轨迹绘制
文章来源地址https://www.toymoban.com/news/detail-760305.html
到了这里,关于opencv——实现智能小车巡线的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!