【问题标题】:cv2.boundingRect returns wrong coordinatescv2.boundingRect 返回错误的坐标
【发布时间】:2018-06-09 15:00:46
【问题描述】:

我尝试在 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() 似乎返回错误坐标的问题。盒子总是在图像的一边。 为什么会这样,我该如何解决?

【问题讨论】:

  • 你打算返回什么?
  • 如果我没看错图片,图片左侧的绿线是边框吗?

标签: python image opencv motion-detection


【解决方案1】:

根据latest documentation ,findContours的返回顺序是图像、轮廓、层次。 所以你的cnts, _, _ = cv2.findContours 应该是_, cnts, _ = cv2.findContours

我没有发现任何其他问题。

【讨论】:

  • 谢谢,成功了。但是要知道边界框似乎随着眼睛的框架而增长,最终占据了大部分图像。
  • 这可能是因为您将矩形绘制到您的代码正在评估的同一图像上(在 cv2.rectangle 调用中)。您应该为可视化创建一个单独的变量。
  • 是的,如@MateusReis 所述,创建原始图像的副本:img_copy = observation.copy();现在对 img_copy() 执行所有后续操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-20
  • 1970-01-01
相关资源
最近更新 更多