Ubuntu:使用cv2.imshow()与pyplot.plot()时出错

2 投票
1 回答
2282 浏览
提问于 2025-04-17 20:55

我正在尝试实现一个简单的直方图计算算法,算法本身运行得很好。但是当我想用cv2.imshow来显示输入图像,然后关闭它,再显示我已经实现的图像直方图时,出现了以下错误:

/usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:无法注册已存在的类型 GtkWidget' g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:无法将类私有字段添加到无效类型 '<invalid>' g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:g_type_add_interface_static: 断言G_TYPE_IS_INSTANTIATABLE (instance_type)' 失败 g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:无法注册已存在的类型 GtkBuildable' g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:g_type_interface_add_prerequisite: 断言G_TYPE_IS_INTERFACE (interface_type)' 失败 g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:142: 警告:g_once_init_leave: 断言 result != 0' 失败 g_type = info.get_g_type() /usr/lib/python2.7/dist-packages/gi/module.py:146: 警告:g_type_get_qdata: 断言node != NULL' 失败 type_ = g_type.pytype

这是我的模块(直方图类)

class Hist(object):


    def __init__(self,image_source):

        self.img_scr = image_source
            self.hist_profile = self.calculate_histogram()

    def calculate_histogram(self):

            row = len(self.img_scr)
            column = len(self.img_scr[0])
            histogram = [0]*256

            for m in range(0,row):
                 for n in range(0,column):
                     pixel_value = self.img_scr[m][n]
                          histogram[pixel_value] += 1

            return histogram

    def plot(self):

            import matplotlib.pyplot as plt
            xAxis = range(0,256)
            yAxis = self.hist_profile
            plt.plot(xAxis,yAxis)
            plt.xlabel('Intensity Value')
            plt.ylabel('Frequency')
            plt.show()

这是一个测试脚本:

import numpy as np
import Histogram as hist


img = cv2.imread('A.jpg',0)
cv2.imshow('Input image',img)
print 'Press any key to continue...'
cv2.waitKey(0)
cv2.destroyAllWindows()


histogram = hist.Hist(img)
histogram.plot()
print 'Press any key to end program.'
cv2.waitKey(0)

/////

当我注释掉其中一个,只使用 cv2.imshow('输入图像', img) 或 histogram.plot() 时,一切都正常。但当我在同一个脚本中同时使用这两个时,错误出现在 cv2.waitKey(0) 之后。

可能是它们之间有冲突,像是窗口处理的问题。我该怎么办呢?

1 个回答

1

问题解决了:

我已经解决了这个问题。问题出在matplotlib的后端,它使用的是gtk+3,而cv2.show()使用的是gtk2.x来处理。

我添加了一行代码:matplotlib.use('GTKAgg'),这样就告诉matplotlib使用gtk2来绘制画布。代码看起来是这样的:

...
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
...

另外,我还把“import matplotlib.pyplot as plt”这行代码移动到了模块文件的最上面,这样一切都正常工作了。

撰写回答