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

只愿长相守 提交于 2020-01-06 19:25:02

问题


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()


来源:https://stackoverflow.com/questions/30069275/opencv-pygi-how-to-display-an-image-read-by-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!