
import cv2
import time,sys,math
import numpy as np
import pygame
from pygame.locals import *
import matplotlib.image as mpimg
from utils import *
if __name__ == "__main__":
cap = cv2.VideoCapture("test.mp4")
FPS = int(round(cap.get(cv2.CAP_PROP_FPS)))
FramePerSec = pygame.time.Clock()
Width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
Height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
scale_ratio = 2
pygame.init()
pygame.display.set_caption('OpenCV Video')
screen = pygame.display.set_mode((Width//2,Height//scale_ratio),0,32)
num = 0
while cap.isOpened():
ret, frame = cap.read()
if num == 0:
T0 = time.time()
if time.time()-T0 > num*(1./FPS):
ret, frame = cap.read()
frame = cv2.resize(frame,(Width//scale_ratio,Height//scale_ratio),interpolation = cv2.INTER_AREA)
thresh_pipeline(frame)
screen.fill([0,0,0])
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.transpose(frame)
frame = pygame.surfarray.make_surface(frame)
screen.blit(frame, (0,0))
pygame.display.update()
num += 1
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
这里使用 pygame 来显示图片,有关 pygame 使用方法还是比较简单,pygame.init()
初始化 pygame 对象,通过调用 pygame 的 display 对象可以调用一些显示相关的方法。例如set_caption("OpenCV Video")
,调用 display 提供的set_model
方法来获取显示窗口 screen ,类似一个画布,然后可以在这个画布上绘制图片和文字。surfarray
的make_surface
的方法来将 frame 生成为 surface 后渲染到 screen 上。然后调用
thresh_pipeline(frame)
HLS(Hue, Saturation, Lightness) 色彩空间
- 色相(Hue): 是色彩的基本属性,就是平常所说的颜色名称,如红色、黄色等。
- 饱和度(Saturation):是指色彩的纯度,越高色彩越纯,低则逐渐变灰,取0-100%的数值。
- 亮度(Lightness):亮度(L),取0-100%。
这里我们为了检测车道线,我们需要将图片置于一个车道线容易识别的色彩空间内。这里使用 HLS 色彩空间来便于检测边缘线
用途

# 转换颜色
hls = cv2.cvtColor(img,cv2.COLOR_RGB2HLS)
# 获取图片的饱和度通道
s_channel = hls[:,:,2]
s_binary = np.zeros_like(s_channel)
s_binary[s_channel >= s_thresh[0] & (s_channel <= s_thresh[1])] = 1
hsv = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
# 获取图片的饱和度通道
v_channel = hsv[:,:,2]
v_binary = np.zeros_like(v_channel)
v_binary[v_channel >= v_thresh[0] & (v_channel <= v_thresh[1])] = 1
c_binary = np.zeros_like(s_channel)
c_binary[(s_binary == 1) & (v_binary==1)] = 1
return c_binary
Sobel
Sobel operator (索贝尔算子)主要用作边缘检测,是一离散性差分算子,用来运算图像亮度函数的灰度之近似值。在图像的任何一点使用此算子,将会产生对应的灰度矢量或是其法矢量。



def abs_sobel_thresh(img,orient='x',sobel_kernel=3,thresh=(0,255)):
# 将图像处理为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
if orient == 'x':
sobel = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=sobel_kernel)
if orient == 'y':
sobel = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=sobel_kernel)
abs_sobel = np.absolute(sobel)
scaled_sobel = np.uint8(255 * abs_sobel/np.max(abs_sobel))
grad_binary = np.zeros_like(scaled_sobel)
grad_binary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
# print(abs_sobel)
return grad_binary
网友评论