我尝试在OpenCV中为Atari游戏构建运动跟踪系统,这样我就可以将这些信息用于强化学习算法。 这是代码:
import gym
import os
import cv2
env = gym.make('Breakout-v0')
def motion_detection(frame1,frame2):
delta = cv2.absdiff(frame1,frame2)[2:-2, 2:-2]
delta = cv2.cvtColor(delta,cv2.COLOR_RGB2GRAY)
cnts, _, _ = cv2.findContours(delta, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
objects = []
for c in cnts:
objects.append(cv2.boundingRect(c))
return objects
observation = env.reset()
f = 0
while True:
f += 1
old_observation = observation
observation, reward, done, info = env.step(env.action_space.sample())
objects = motion_detection(old_observation,observation)
for obj in objects:
x,y,w,h = obj
cv2.rectangle(observation,(x,y),(x+w,y+h),(0,255,0),1)
cv2.imwrite(os.getcwd()+'/'+str(f)+'.png',observation)
if done:
break
现在我遇到了函数cv2.boundingRect()
似乎返回错误坐标的问题。 Box始终位于Image的侧面。
为什么这样,我该如何解决?
答案 0 :(得分:0)
根据latest documentation
,findContours的返回顺序是图像,轮廓,层次结构。
因此,cnts, _, _ = cv2.findContours
应为_, cnts, _ = cv2.findContours
。
我没有看到任何其他问题。