在 BGR 比例中看不到帧 (OpenCV)

Frames are not seen in BGR scale (OpenCV)

我正在尝试使用 OpenCV 从头开始​​编写 SLAM 代码。当我尝试用彩色圆形标记显示每个帧中检测到的特征时,我在用颜色显示时遇到了问题。

总结

我希望框架中有彩色圆形标记,但目前看不到。

#! /usr/bin/env python3
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

W = 1920//2
H = 1080//2


def process(image):
    image = cv.resize(image,(W,H))
    image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    corners = cv.goodFeaturesToTrack(image, 3000, 0.01, 3)
    corners = np.int0(corners)
    image_copy = cv.cvtColor(image, cv.COLOR_GRAY2BGR)

    for i in corners:
        x, y = i.ravel()
        cv.circle(image_copy, (x,y), color = (0,0,255), radius=3)
        #cv.circle(image, (x,y), 3, 255, -1)
     
    return image_copy



if __name__ == "__main__":
    cap = cv.VideoCapture("../test/test_countryroad.mp4")

    while cap.isOpened():
        ret, frame = cap.read()
        if ret == True:
            frame = process(frame)
            frame = cv.cvtColor(frame, cv.COLOR_GRAY2RGB)
            cv.imshow('frame', frame)
            if cv.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

    cap.release()
    cv.destroyAllWindows()

但是在我运行这段代码后出现如下错误。

Traceback (most recent call last):
  File "./slam.py", line 34, in <module>
    frame = cv.cvtColor(frame, cv.COLOR_GRAY2RGB)
cv2.error: OpenCV(4.2.0) /home/hkim/opencv/opencv-4.2.0/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl::{anonymous}::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::impl::{anonymous}::Set<1>; VDcn = cv::impl::{anonymous}::Set<3, 4>; VDepth = cv::impl::{anonymous}::Set<0, 2, 5>; cv::impl::{anonymous}::SizePolicy sizePolicy = (cv::impl::<unnamed>::SizePolicy)2; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 3

我该如何解决?

您的图像是灰度图像,因此当您尝试在图像中绘制彩色圆圈时,您做不到,因为只有一个通道,而不是彩色图像预期的三个通道。您需要做的是创建一个单独的框架副本,这样您就可以 运行 对其进行兴趣点检测,获取角并将它们绘制在图像的彩色版本上。

def process(image):
    image = cv.resize(image,(W,H))
    # Change
    image_copy = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    # Change
    corners = cv.goodFeaturesToTrack(image_copy, 3000, 0.01, 3)
    corners = np.int0(corners)

    for i in corners:
        x, y = i.ravel()
        cv.circle(image, (x,y), color = (0,0,255), radius=3)

    return image

最后在你的 while 循环中,因为图像现在是彩色的,你可以删除从灰度到彩色的转换语句作为函数 returns 图像已经是彩色的。

   while cap.isOpened():
        ret, frame = cap.read()
        if ret == True:
            frame = process(frame)
            # Remove the line below
#            frame = cv.cvtColor(frame, cv.COLOR_GRAY2RGB)
            cv.imshow('frame', frame)
            if cv.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break