1

在调试 C++ OpenCV 程序时,我想在 GDB 下的程序中看到一个图像,我的意思是我想在 GDB 下可视化数据。幸运的是我有:

  1. 支持 python 的 GDB;
  2. 我已经安装了python 2.7.4、numpy库和opencv正式版2.4.4;
  3. 我已将 python 接口文件“cv2.pyd”安装到我的 python 站点包文件夹中。

现在,我可以运行一个纯 python 脚本来加载和显示图像。但是当我尝试显示来自 GDB 的图像时,我的问题就出现了。(图像在我的 C++ 程序中)

#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv; 
...
Mat orgImg = imread("1.jpg", CV_LOAD_IMAGE_GRAYSCALE);

然后我设置了一个断点,然后 GDB 命中断点,我在 GDB 的命令行中运行这样的命令

source test.py

test.py 是一个尝试显示图像的 python 脚本:

import gdb
import cv2
import numpy

class PlotterCommand(gdb.Command):
    def __init__(self):
        super(PlotterCommand, self).__init__("plot",
                                             gdb.COMMAND_DATA,
                                             gdb.COMPLETE_SYMBOL)
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
        v = gdb.parse_and_eval(args[0])
        t = v.type.strip_typedefs()
        print t
        a = numpy.asarray(v)
        cv2.namedWindow('debugger')
        cv2.imshow('debugger',a)
        cv2.waitKey(0)

PlotterCommand()

之后,我只运行命令

plot orgImg

但是 GDB 得到一个错误:

cv::Mat
Python Exception <type 'exceptions.TypeError'> mat data type = 17 is not supported: 
Error occurred in Python command: mat data type = 17 is not supported
Error occurred in Python command: mat data type = 17 is not supported

你看,GDB下的python对象是"cv::Mat",但是它不能转换成正确的python对象来显示。任何人都可以帮助我吗?谢谢。

编辑: 我尝试创建一个使用 cv(不是 cv2)的更简单的脚本,但它仍然不起作用:

import gdb
import cv2.cv as cv

class PlotterCommand(gdb.Command):
    def __init__(self):
        super(PlotterCommand, self).__init__("plot",
                                             gdb.COMMAND_DATA,
                                             gdb.COMPLETE_SYMBOL)
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
        v = gdb.parse_and_eval(args[0])  
        a = cv.CreateImageHeader((v['cols'],v['rows']), cv.IPL_DEPTH_8U, 1)
        cv.SetData(a, v['data'])
        cv.NamedWindow('debugger')
        cv.ShowImage('debugger', a)
        cv.WaitKey(0)

PlotterCommand()

上面的代码不起作用,因为语句“cv.SetData(a, v['data'])”并没有真正进行缓冲区地址分配。

“v”是 cv::Mat 的表示形式,其内容如下:

{flags = 1124024320, dims = 2, rows = 44, cols = 37, data = 0x3ef2d0 '\377' <repeats 200 times>..., refcount = 0x3ef92c, datastart = 0x3ef2d0 '\377' <repeats 200 times>..., dataend = 0x3ef92c "\001", datalimit = 0x3ef92c "\001", allocator = 0x0, size = {p = 0x22fe10}, step = {p = 0x22fe38, buf = {37, 1}}}

因此,您看到“数据”字段是原始缓冲区指针,但我不确定如何将此 gdb.Value 传输到 python 缓冲区类型。

4

2 回答 2

2

我现在已经解决了这个问题,这里有一些小问题的解决方案(见下文)

假设你有这样的 C++ 代码:

#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv; 
...
Mat img = imread("1.jpg", CV_LOAD_IMAGE_GRAYSCALE);
...

在 GDB 下调试这些代码时,我想看看内存数据“img”的样子。感谢 GDB 和 OpenCV,它们都有 Python 接口,所以这里是 python 漂亮的脚本(我在 GPLv3 下发布了脚本代码)

在此之前,你需要 1、GDB with python enabled 2、OpenCV python interface(Windows下是一个文件cv2.pyd) 3、安装python、numpy

############################################################
#filename: cvplot.py
import gdb
import cv2.cv as cv
import sys


class PlotterCommand(gdb.Command):
    def __init__(self):
        super(PlotterCommand, self).__init__("plot",
                                             gdb.COMMAND_DATA,
                                             gdb.COMPLETE_SYMBOL)
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)


        # generally, we type "plot someimage" in the GDB commandline
        # where "someimage" is an instance of cv::Mat
        v = gdb.parse_and_eval(args[0])

        # the value v is a gdb.Value object of C++
        # code's cv::Mat, we need to translate to
        # a python object under cv2.cv
        image_size =  (v['cols'],v['rows'])
        # print v
        # these two below lines do not work. I don't know why
        # channel = gdb.execute("call "+ args[0] + ".channels()", False, True)
        # channel = v.channels();
        CV_8U =0
        CV_8S =1
        CV_16U=2
        CV_16S=3
        CV_32S=4
        CV_32F=5
        CV_64F=6
        CV_USRTYPE1=7
        CV_CN_MAX = 512
        CV_CN_SHIFT = 3
        CV_MAT_CN_MASK = (CV_CN_MAX - 1) << CV_CN_SHIFT
        flags = v['flags']
        channel = (((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1
        CV_DEPTH_MAX = (1 << CV_CN_SHIFT)
        CV_MAT_DEPTH_MASK = CV_DEPTH_MAX - 1
        depth = (flags) & CV_MAT_DEPTH_MASK
        IPL_DEPTH_SIGN = 0x80000000
        cv_elem_size = (((4<<28)|0x8442211) >> depth*4) & 15
        if (depth == CV_8S or depth == CV_16S or depth == CV_32S):
                mask = IPL_DEPTH_SIGN
        else:
                mask = 0
        ipl_depth = cv_elem_size*8 | mask     
        img = cv.CreateImageHeader(image_size, ipl_depth, channel)

        # conver the v['data'] type to "char*" type
        char_type = gdb.lookup_type("char")
        char_pointer_type =char_type.pointer()
        buffer = v['data'].cast(char_pointer_type)

        # read bytes from inferior's memory, because
        # we run the opencv-python module in GDB's own process
        # otherwise, we use memory corss processes        
        buf = v['step']['buf']
        bytes = buf[0] * v['rows'] # buf[0] is the step? Not quite sure.
        inferior = gdb.selected_inferior()
        mem = inferior.read_memory(buffer, bytes)

        # set the img's raw data
        cv.SetData(img, mem)

        # create a window, and show the image
        cv.NamedWindow('debugger')
        cv.ShowImage('debugger', img)

        # the below statement is necessory, otherwise, the Window
        # will hang
        cv.WaitKey(0) 

PlotterCommand()
############################################################

上面的脚本添加了一个新的 GDB 命令“plot”来显示内存数据 cv::Mat。现在,您可以简单地键入:“source cvplot.py”将此脚本加载到 GDB,然后键入:“plot img”以在 OpenCV 的窗口中显示 cv::Mat,让 GDB 继续,只需关闭调试器窗口即可。

顺便说一句:我发现了一个问题,如果我在脚本源中取消注释“# print v”,那么这个脚本会抱怨这样的消息并中止:

Python Exception <type 'exceptions.UnicodeEncodeError'> 'ascii' codec can't encode characters in position 80-100: ordinal not in range(128): 
Error occurred in Python command: 'ascii' codec can't encode characters in position 80-100: ordinal not in range(128)

但是如果我直接在 GDB 的命令行中运行命令“print img”,它会显示:

$2 = {flags = 1124024320, dims = 2, rows = 243, cols = 322, data = 0xb85020 "\370\362èèé?èè?èé?è?è?èèèèèèè\372\357èèèèèèèèèèèèèèè?è?èèèè???èè?èéèèè?èè??èèèéèééèèèèèèèèèèèèèèèè?è?èèèèèèè?èèè?è"..., refcount = 0xb981c8, datastart = 0xb85020 "\370\362èèé?èè?èé?è?è?èèèèèèè\372\357èèèèèèèèèèèèèèè?è?èèèè???èè?èéèèè?èè??èèèéèééèèèèèèèèèèèèèèèè?è?èèèèèèè?èèè?è"..., dataend = 0xb981c6 "\255\272\001", datalimit = 0xb981c6 "\255\272\001", allocator = 0x0, size = {p = 0x22fe64}, step = {p = 0x22fe8c, buf = {322, 1}}}

我不知道如何解决这个问题,但我肯定可以看到 python 尝试将原始缓冲区解码为普通文本是一些问题。(我使用的是 WinXP)

非常感谢 Tromey、Andre_、Pmuldoon 对 GDB IRC 的帮助,也感谢慧宁的大力帮助和建议,解决方案也发布在 GDB 邮件列表中 发布在 GDB 邮件列表中,我也想将此贡献给 OpenCV 社区Visualize在内存中来自 GDB 漂亮打印机的 OpenCV 图像或矩阵

于 2013-12-09T09:33:20.713 回答
1

您需要 lower.read_memory 将 pixmap 内容从调试程序传输到 gdb 进程。也许查看 Qt Creator 实现,它具有类似的功能来显示 QImage 数据。

于 2013-04-27T12:48:03.617 回答