本次測量的物體為:一個綠色小瓶蓋
首先得通過閾值編譯器得到這個綠色小瓶蓋得閾值:
代碼如下:
import sensor, image, time #導入模塊
# For color tracking to work really well you should ideally be in a very, very,
# very, controlled enviroment where the lighting is constant...
red_threshold = (100, 0, 127, 13, -104, 85) #紅色閾值
green_threshold = (93, 18, -122, -13, 16, 127) #黃色閾值
blue_threshold = (0,15,0,40,-80,-20) #藍色閾值
# You may need to tweak the above settings for tracking green things...
# Select an area in the Framebuffer to copy the color settings.
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
sensor.skip_frames(10) # Let new settings take affect.
sensor.set_auto_whitebal(False) # 關閉白平衡,以防顏色干擾
clock = time.clock() # Tracks FPS.
#注意:每次更換物體,需要重新測量K1、K2、K3
K1=540 #需要自己計算,K1=距離(12cm已知)*直徑像素Lm(45)
K2=3/46 #需要自己計算,K2=實際大小(寬3cm已知)/寬像素b[2](46)
K3=3/42 #需要自己計算,K3=實際大小(高3cm已知)/高像素b[3](42)
while(True):
clock.tick() # Track elapsed milliseconds between snapshots().
img = sensor.snapshot() # Take a picture and return the image.
blobs = img.find_blobs([green_threshold])
if len(blobs) == 1:
# Draw a rect around the blob.
b = blobs[0]
img.draw_rectangle(b[0:4]) # rect,矩形框
img.draw_cross(b[5], b[6]) # cx, cy,物體坐標,畫十字
Lm = (b[2]+b[3])/2 #b[2]為寬,b[3]為長,計算得到Lm——直徑像素
print("直徑像素是:",Lm) #輸出直徑像素,來計算K1
print("寬像素是:",b[2]) #輸出寬度的像素,來計算K2
print("高像素是:",b[3]) #輸出長度的像素,來計算K3
distance = K1/Lm #求距離的公式
width = K2*b[2]
height = K3*b[3]
print("距離是:",distance) #測距
print("寬是:%f,長是:%f"%(width,height)) #測量物體大小
測量結果如下:
該測量值與實際值有一定的誤差,但是誤差不大!
注意:每次更換物體,需要重新測量K1、K2、K3
正是步行者,一步步登峰!