python opencv 画点,OpenCV python:如何使用渐变和第一个点画一条线?

本文介绍了一种使用OpenCV库在连续帧中绘制物体移动轨迹的方法。通过获取物体的坐标,并利用这些坐标来计算斜率,从而可以预测并绘制物体的运动轨迹。此方法适用于实时视频流的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am trying to draw a line using a live feed with opencv. I am using one frame and storing the x,y coordinates. I use the next frame's x,y coordinate of the point to work out the gradient ((y2-y1)/(x2-x1)). I want to draw a straight line from the first coordinate straight through the second and continue past which would draw a trajectory. I can currently draw a straight line between the two points using cv2.line(). My code is below. Any suggestions would be wonderful! Thank you

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()

解决方案

Found a solution from this answer which was in c, Converted to python and modified for your usecase.

Solution to draw infinte line in image given two points.

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)

you can replace (px,py) with (x1,y1) or (qx,qy) with (x2,y2) according to your usecase.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值