0.前言
为了学习与了解opencv与图像处理相关的知识,实现台球小游戏的指示线延长。
1.实现
1.屏幕区域截图
先安装pyautogui库,在终端中输入:
pip install pyautogui
利用以下代码实现屏幕截取。region中的前两个变量为起点,后两个参数为截取屏幕的长与宽。
img = pyautogui.screenshot(region=[120, 160, 810, 450]) # x,y,w,h
2.特定颜色提取
为了提取台球桌画面的白色线条,首先需要选取白色的hsv范围,需要将图片转换为hsv格式,mask1中显示得到的hsv筛选结果,使用src显示图片。
hsv = cv.cvtColor(np.asarray(img), cv.COLOR_BGR2HSV)
mask1 = cv.inRange(hsv, (0, 0, 221), (0, 15, 255))
src = cv.cvtColor(np.asarray(img), cv.COLOR_BGR2RGB)
3.霍夫直线检测
使用opencv提供的方法进行霍夫直线检测。具体参数大家可自行查阅资料进行调整。
linesP = cv.HoughLinesP(mask1, 1, np.pi / 180, 10, None, 5, 10)
4.直线筛选
选取出特定长度的线段,再将直线进行延长与绘画。
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
if (l[2] - l[0] ) is not 0:
k = (l[3] - l[1] )/ (l[2] - l[0] +0.0001)
x1=l[0]
y1=l[1]
x2=l[2]
y2=l[3]
if abs(x1 - x2) + abs(y1 - y2) < 50 and k< 999:
xmin = 820
xmax = 0
for x in range(1, 809):
y = k * (x - x1) + y1
if y > 0 and y < 449:
if x < xmin:
xmin = x
if x > xmax:
xmax = x
cv.line(src, (xmin, int(k*(xmin-x1)+y1)), (xmax, int(k*(xmax-x1)+y1)), (0, 255, 0), 1, cv.LINE_AA)
2.运行结果
3.完整代码
import cv2 as cv
import numpy as np
import pyautogui
while 1:
img = pyautogui.screenshot(region=[120, 160, 810, 450]) # x,y,w,h
hsv = cv.cvtColor(np.asarray(img), cv.COLOR_BGR2HSV)
src = cv.cvtColor(np.asarray(img), cv.COLOR_BGR2RGB)
cv.namedWindow("t", cv.WINDOW_AUTOSIZE)
mask1 = cv.inRange(hsv, (0, 0, 221), (0, 15, 255))
linesP = cv.HoughLinesP(mask1, 1, np.pi / 180, 10, None, 5, 10)
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
if (l[2] - l[0] ) is not 0:
k = (l[3] - l[1] )/ (l[2] - l[0] +0.0001)
x1=l[0]
y1=l[1]
x2=l[2]
y2=l[3]
if abs(x1 - x2) + abs(y1 - y2) < 50 and k< 999:
xmin = 820
xmax = 0
for x in range(1, 809):
y = k * (x - x1) + y1
if y > 0 and y < 449:
if x < xmin:
xmin = x
if x > xmax:
xmax = x
cv.line(src, (xmin, int(k * (xmin - x1) + y1)), (xmax, int(k * (xmax - x1) + y1)),
(0, 255, 0), 1, cv.LINE_AA)
cv.imshow("t", src)
cv.waitKey(10)
cv.destroyAllWindows()