所以我和我的朋友们正在组装这个自制的激光测距仪,有人在这个网站上贴出了这样的信息:http://shaneormonde.wordpress.com/2014/01/25/webcam-laser-rangefinder/。在进入python代码部分之前,一切都进行得很顺利,因为我们不熟悉任何编程语言。正如网站上的项目所描述的那样,它应该在摄像头的视野中检测到一个红色的点。不幸的是,我们已经买了一台绿色激光。如何更改代码,使其检测绿色点?以下是代码:
## 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 " 发布于 2015-01-11 11:20:10
rval, frame = vc.read()以BGR格式读取图像。您直接链接的教程页面是这样的。
因此,所有像素数据都存储在一个名为frame的numpy数组中。默认情况下,opencv获取640 x 480图像(x轴上为640,y为480 )。numpy数组具有三维(x)(y)(BGR),因此前两个维度在每个维度中只有一个数字,指定像素的x或y坐标。第三维空间包含三个数字,即该像素的RGB内容。尽管出于某种原因,这些值被安排为BGR。
因此,改变路线
num = (frame[...,...,2] > 236)至
num = (frame[...,...,1] > 236)应该为你做点什么。
为了非常简单地解释这条线的作用,它在彩色平面上检查高强度值(超过236个,其中min=0和max=255),并记录所有这些像素。这个想法是,如果你用红色的激光,红色的平面将有一个高强度的浓度值在圆点区域周围。
https://stackoverflow.com/questions/27886053
复制相似问题