Opencv & PyGi : how to display an image read by op

2019-09-02 14:53发布

问题:

I want to display an image in PyGi, the image is read first by opencv. But,it fails.

from gi.repository import Gtk, GdkPixbuf
import cv2
import numpy as np
window = Gtk.Window()
image = Gtk.Image()
image.show()
window.add(image)
window.show_all()
im = cv2.imread("file.bmp")
a = np.ndarray.tostring(img)
h, w, d = img.shape
p = GdkPixbuf.Pixbuf.new_from_data(a,GdkPixbuf.Colorspace.RGB, False, 8, w, h, w*3, None, None)
image.set_from_pixbuf(p)
Gtk.main()

But the result is a black image. Moreover, if I loop around a set of files (multiple .bmp files from a directory), I got coredump (suspecting GdkPixbuf.Pixbuf.new_from_data)

Is it the proper way to have opencv & PyGi interacting ? I managed to use opencv with Tkinter, but I fail to use it with PyGi.

回答1:

You can try using GdkPixbuf.PixbufLoader:

loader = GdkPixbuf.PixbufLoader()
loader.write(img)
loader.close()
pixbuf = loader.get_pixbuf()
image = Gtk.Image.new_from_pixbuf(pixbuf)


回答2:

This actually worked just fine for me. Perhaps the issue in your case was the two different variables 'im' (in which you are reading the CV image) and 'img' (the one that you are converting to string)?

Here is a simplified code that worked for me in displaying a video frame from camera:

# OpenCV image:
cap = cv2.VideoCapture(0)
ret, img = cap.read()
# Gtk Image:
img_gtk = Gtk.Image()
# Do other things such as attaching the 'img_gtk' to a window/grid...

# Convert and display:
h, w, d = img.shape
pixbuf = GdkPixbuf.Pixbuf.new_from_data  (img.tostring(), GdkPixbuf.Colorspace.RGB, False, 8, w, h, w*3, None, None)
img_gtk.set_from_pixbuf (pixbuf)
img_gtk.show()