我是python语言的新手,我一直试图改变Shaneormonde在这个优秀教程中找到的代码:
https://shaneormonde.wordpress.com/2014/01/25/webcam-laser-rangefinder/
我已经复制了我对下面感兴趣的确切代码:
## program written by Shane Ormonde 7th sept 2013
## updated on 25th January 2014
## calculates the distance of a red dot in the field of view of the webcam.
import cv2
from numpy import *
import math
#variables
loop = 1
dot_dist = 0
cv2.namedWindow("preview")
vc = cv2.VideoCapture(1)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
#print "failed to open webcam"
if rval == 1 :
while loop == 1:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
loop = 0
num = (frame[...,...,2] > 236)
xy_val = num.nonzero()
y_val = median(xy_val[0])
x_val = median(xy_val[1])
#dist = ((x_val - 320)**2 + (y_val - 240)**2 )**0.5 # distance of dot from center pixel
dist = abs(x_val - 320) # distance of dot from center x_axis only
print " dist from center pixel is " + str(dist)
# work out distance using D = h/tan(theta)
theta =0.0011450*dist + 0.0154
tan_theta = math.tan(theta)
if tan_theta > 0: # bit of error checking
obj_dist = int(5.33 / tan_theta)
print "\033[12;0H" + "the dot is " + str(obj_dist) + "cm away"
elif rval == 0:
print " webcam error "
我已经能够使用他网站上列出的网络摄像头和激光指示器来使用此代码。但我想改变他的代码,以便使用激光线,而不是只是一个点。因此,我将计算整个激光线的距离,而不仅仅是一个点。与此示例非常相似的东西:
https://www.youtube.com/watch?v=DXeia4NFbx8
但是因为我对python很陌生,所以我不知道如何调整上面的代码来计算激光线上的距离,而不是仅仅一点。
任何有关调整上述代码的帮助(或者如果您提供自己的代码,都会非常感谢)。