python - OpenCV python:如何使用渐变和第一点画一条线?
问题描述
我正在尝试使用带有 opencv 的实时提要画一条线。我正在使用一帧并存储 x,y 坐标。我使用该点的下一帧的 x,y 坐标来计算梯度 ((y2-y1)/(x2-x1))。我想从第一个坐标直接到第二个坐标画一条直线,然后继续画一条轨迹。我目前可以使用 . 在两点之间画一条直线cv2.line()
。我的代码如下。任何建议都会很棒!谢谢
import numpy as np
import math
import matplotlib.pyplot as plt
lower_red = np.array([-10,160,160])
upper_red = np.array([10,255,255])
oX, oY = 0,0
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
while(1):
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower_red, upper_red)
#ret, thresh = cv2.threshold(mask, 80, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
if len(contours) != 0:
c = max(contours, key = cv2.contourArea)
x1, y1, w, h = cv2.boundingRect(c)
x2, y2 = x1 + w, y1 + h
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
x3, y3 = round((x1+x2)/2), round((y1+y2)/2)
cv2.circle(frame, (x3,y3), 4, (255,0,0), 2)
#print(x3, y3)
if oX and oY != 0:
try:
angle = (x3-oX)/(y3-oY)
cv2.line(frame,(oX,oY),(x3, y3),(0,255,255),2)
except ZeroDivisionError:
oX, oY = x3, y3
oX, oY = x3, y3
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
if cv2.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
解决方案
从这个答案中找到了一个解决方案,它在 c 中,转换为 python 并针对您的用例进行了修改。
给定两点在图像中绘制无限线的解决方案。
def slope(x1,y1,x2,y2):
###finding slope
if x2!=x1:
return((y2-y1)/(x2-x1))
else:
return 'NA'
def drawLine(image,x1,y1,x2,y2):
m=slope(x1,y1,x2,y2)
h,w=image.shape[:2]
if m!='NA':
### here we are essentially extending the line to x=0 and x=width
### and calculating the y associated with it
##starting point
px=0
py=-(x1-0)*m+y1
##ending point
qx=w
qy=-(x2-w)*m+y2
else:
### if slope is zero, draw a line with x=x1 and y=0 and y=height
px,py=x1,0
qx,qy=x1,h
cv2.line(image, (int(px), int(py)), (int(qx), int(qy)), (0, 255, 0), 2)
您可以根据您的用例替换(px,py)
为(x1,y1)
或。(qx,qy)
(x2,y2)
推荐阅读
- javascript - vue 组件没有渲染从后端获取的数据
- bash - Github 自动更新与 cron
- javascript - Express 没有渲染我的 React 前端?
- python - 如何在'\n'处将一个列表分成两个列表?
- php - Symfony 表单错误:必须管理传递给选择字段的“...”类型的实体。可能你忘记在实体管理器中持久化
- javascript - 如何在我的 functions.php 中做一个 IF 语句来确定我是否在单打产品页面上?(woocommerce)
- python - 为什么我收到 ImportError: cannot import name 'fore' from 'colorama'?
- ruby-on-rails - rails 将 datetime db 列设置为与 updated_at 相同的值
- python - Pandas 合并功能仅显示列标题
- c# - 如何使用嵌套的 switch 语句将数字转换为 0 - 9999 范围内的单词