索引错误:列出索引超出范围 - 如果我的运动传感器没有检测到运动或检测到太多运动,为什么它会崩溃?



我一直在使用python和pygame构建一个运动传感器,它基本上会拍摄您的相机镜头的照片,将每个像素的RGB值与上次拍摄的照片进行比较,并显示pygame屏幕中已更改的像素。由于某些原因,如果它检测到太多的运动(例如你覆盖了相机),或者如果它检测到太少(例如你停止移动一段时间),它将崩溃。

代码:

import pygame
from pygame.locals import *
import pygame.camera
import pygame.image
import numpy as np
import cv2
pygame.init()
pygame.camera.init()
pygame.display.set_caption("Game")
cameras = pygame.camera.list_cameras()
print("Using camera %s ..." % cameras[0])
cam1 = pygame.camera.Camera(cameras[0])
cam1.start()
img1 = cam1.get_image()
flags = DOUBLEBUF
screen = pygame.display.set_mode((500,500), flags, 4)
frame = 0
def take_screen_shot():
global frame
save_file = str(frame)+'.png'#save file
pygame.image.save(img1, save_file)
def image_proccesing():
global frame
global counter
if frame >= 1:
img1 = cv2.imread(str(frame - 1)+'.png', 0)
img2 = cv2.imread(str(frame)+'.png', 0)
sub = cv2.subtract(img1, img2)
coords = np.argwhere(sub > 100)#checks if the pixels have a difference bigger than 100
coords_list = coords.tolist()#converts the array into a list
x = list(list(zip(*coords_list))[0])#grabs the first value, in this case x coordenates
y = list(list(zip(*coords_list))[1])#grabs the first value, in this case y coordenates
for i in range(len(x)):
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(y[i], x[i], 1, 1))
x.clear()
y.clear()
clock = pygame.time.Clock()
while 1:
screen.fill((0, 0, 0))
for event in pygame.event.get():
pygame.event.set_allowed(KEYDOWN)
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
pygame.camera.quit()
img1 = cam1.get_image().convert()
take_screen_shot()
image_proccesing()
clock.tick(15)
pygame.display.update()
frame += 1

错误:

x = list(list(zip(*coords_list))[0])
IndexError: list index out of range

我已经发现了错误,我必须检查文件是否有任何值。我通过改变image_proccesing函数来做到这一点。

image_proccesing:

global frame
global counter
if frame >= 1:
img1 = cv2.imread('screenshots\'+str(frame - 1)+'.png', 0)
img2 = cv2.imread('screenshots\'+str(frame)+'.png', 0)
sub = cv2.subtract(img1, img2)
coords = np.argwhere(sub > 100)
coords_list = coords.tolist()
if coords_list:
x = list(list(zip(*coords_list))[0])
y = list(list(zip(*coords_list))[1])
for i in range(len(x)):
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(y[i], x[i], 1, 1))
if (x[i] > values[0][0] and x[i] < values[1][0]):
if (y[i] > values[1][1] and y[i] < values[0][1]):
print('ayo')
x.clear()
y.clear()

最新更新