import sensor, image, time
# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
thread=(50,255,-128,127,-128,127)
sensor.set_auto_whitebal(False)
sensor.set_contrast(5)
# 创建两个图像缓冲区last_frame是背景
current_frame = sensor.snapshot()
#last_frame = current_frame.copy()
last_update_time = 0
person=0
while(True):
x=0
y=0
ry=0
rx=0
i=0
# 获取当前帧并计算差分图像
current_frame = sensor.snapshot()
if time.time() - last_update_time > 0.5 :
#sensor.snapshot().save("bg.bmp")
last_frame = current_frame.copy()
last_update_time = time.time()
diff_frame = current_frame.difference(last_frame)
# 对差分图像进行阈值分割和形态学操作
threshold = (50, 255)
binary_frame = diff_frame.to_grayscale()
binary_frame.binary([threshold])
binary_frame.erode(1)
binary_frame.dilate(4)
# 检测阈值
ROI = (0, 0, binary_frame.width(), binary_frame.height())
statistics=binary_frame.get_statistics(roi=ROI)
gray_count=statistics.mean()
#print("目标区域:", gray_count)
if gray_count>50:
person=1
last_update_time = time.time()
if gray_count<50:
person=0
# 进行连通性分析并绘制矩形框
blobs = binary_frame.find_blobs([thread],area_threshold=2, pixels_threshold=2,merge=False)
for blob in blobs:
if blob.pixels() > 1000:
current_frame.draw_rectangle(blob.rect())
i=i+1
x=x+blob.cx()
y=y+blob.cy()
if i>0:
x=x/i
y=y/i
rx=x/binary_frame.width()
ry=y/binary_frame.height()
print("色块数:", i,"x:",x,"y:",y)
print("x的相对位置",rx,"y的相对位置",ry)
time.sleep(0.1)
```![0_1705200390750_微信图片_20240114104601.png](https://fcdn.singtown.com/12edd7d6-e462-4d79-87c4-71e39a88fad8.png)