Using ImageGrab with bbox from pywin32's GetWindowRect - python

I want to use PIL's ImageGrab to capture a specific window. What my code below does is that it uses pywin32's FindWindow to get the handle of my wanted window then get its size and location with GetWindowRect. I then use ImageGrab with a bbox equal to the result that I got from GetWindowRect. However, this does not capture the whole window; a big chunk of the window is not shown. What did I do wrong? Here is my code and the result I get:
import win32gui
import cv2
from PIL import ImageGrab
import numpy as np
fceuxHWND = win32gui.FindWindow(None, 'FCEUX 2.1.4a: Super Mario Bros. (JU)
[!]')
rect = win32gui.GetWindowRect(fceuxHWND)
screen = np.array(ImageGrab.grab(bbox=rect), dtype=np.uint8)
cv2.imshow('test',cv2.cvtColor(screen,cv2.COLOR_BGR2RGB))
Result of code

Your DPI settings is at 125% and your process is not DPI aware. Call SetProcessDPIAware as follows
import ctypes
...
ctypes.windll.user32.SetProcessDPIAware()

Related

Gtk Warning Theme parsing error, trying to do some facial recognition

i'm having what i think is a gtk error in python while trying to recognize some faces and then apply a gaussian blur, i'm new in python! Here is the error:
*Gtk-WARNING *: 00:11:03.559: Theme parsing error: gtk.css:6321:10: "height" is not a valid property name
i'm currently using Archlinux and python 3+, i checked ~/.config and my Gtk is 2.0, idk if that is the issue and i also don't know how to change it/ update it.
Here is the code i'm triying to compile:
from skimage.filters import gaussian
from skimage import color
from skimage import data
import scipy.misc
import os
import sys
import plots
import matplotlib.pyplot as plt
from PIL import Image
path = "/home/carlos/python/img/jaja.jpeg"
img = plt.imread("/home/carlos/python/img/girl.jpeg")
#plt.show(img)
trained_file = data.lbp_frontal_face_cascade_filename()
detector = Cascade(trained_file)
detected = detector.detect_multi_scale(img=img, scale_factor=1.2, step_ratio=1, min_size=(50,50), max_size=(200,200))
print(detected)

Image in TreeView not showing Tkinter

I am making a TreeView in Tkinter Python 3.4 I have added a chrome logo but the image never appears.
treeview=ttk.Treeview(frame3)
chromelogo=PhotoImage(file="./Images/minor-logo.png")
chromelogo=chromelogo.subsample(10,10)
treeview.pack(fill=BOTH,expand=True)
treeview.insert('','0','Chrome',text='Chrome', image=chromelogo)
treeview.insert('Chrome','0',"shit",text="shit",image=chromelogo)
treeview.insert('','1','Chrome3',text='Chrome3')
The link for chrome logo: http://logos-download.com/wp-content/uploads/2016/05/Chrome_icon_bright.png
Photoimage doesn't let you open images rather that a gif type if you want to open an image rather than gif in tkinter try the PIL module. you could use any method to install the PIL module, i like the command line
python -m pip install pillow
since you want to your image to feet in the tree view use this to resize and insert it
from tkinter import *
from tkinter import ttk
from PIL import ImageTk,Image
win=Tk()
chromelogo=Image.open("./Images/minor-logo.png")#open the image using PIL
imwidth=10#the new width you want
#the next three lines of codes are used to keep the aspect ration of the image
wpersent=(imwidth/float(chromelogo.size[0]))
hsize=int(float(chromelogo.size[1])*float(wpersent))#size[1] means the height and the size[0] means the width you can read more about this in th PIL documentation
chromelogo=ImageTk.PhotoImage(chromelogo.resize((imwidth,hsize),Image.ANTIALIAS))# set the width and put it back in the chromelogo variable
treeview=ttk.Treeview(win)
treeview.pack(fill=BOTH,expand=False)
treeview.insert('','0','Chrome',text='Chrome', image=chromelogo)
treeview.image = chromelogo#this one is for telling tkinter not to count the image as garbage
treeview.grid(row=0,rowspan=2,columnspan=2,padx=220,sticky=N+W,pady=20)
chromelogo2=ImageTk.PhotoImage(Image.open("./Images/minor-logo.png"))
treeview.insert('Chrome','0',"shit",text="shit",image=chromelogo2)#here you can also insert the unresized logo so you could see it as big as it is
treeview.insert('','1','Chrome3',text='Chrome3')
win.mainloop()
Simply converting "chromelogo" into a class variable by using the self keyword should fix the problem:
treeview=ttk.Treeview(frame3)
self.chromelogo=PhotoImage(file="./Images/minor-logo.png")
self.chromelogo=self.chromelogo.subsample(10,10)
treeview.pack(fill=BOTH,expand=True)
treeview.insert('','0','Chrome',text='Chrome', image=self.chromelogo)
treeview.insert('Chrome','0',"shit",text="shit",image=self.chromelogo)
treeview.insert('','1','Chrome3',text='Chrome3')

Access qrpython images without writing them to file

Here's my problem.
I'm building a simple QR-code generator with qrcode and PyQt4. In particular, this application shows an image of the generated QR-code inside a QPixmap of a QLabel. The problem is that the qrmodule, as far as I know, allows only to save the generated image to a file. I tried to access the inner workings of qrcode but it's kind of convoluted.
Do you know if it's possible to expose the image by saving the resulting image in a file stream, like the one from tempfile.TemporaryFile()? Otherwise I can only insert the qr-code by saving it on a real file and then loading it. For example
import qrcode as q
from PyQt4 import QtGui
filename = 'path/to/file.png'
img = q.make('Data')
img.save(filename)
pixmap = QtGui.QPixmap(filename)
EDIT 1
I tried to use the PIL.ImageQt.ImageQt function as proposed in an answer in the following way
import sys
import qrcode as qr
from PyQt4 import QtGui
from PIL import ImageQt
a = QtGui.QApplication(sys.argv)
l = QtGui.QLabel()
pix = QtGui.QPixmap.fromImage(ImageQt.ImageQt(qr.make("Some test data")))
l.setPixmap(pix)
l.show()
sys.exit(a.exec_())
The result is not however consistent. This is the result obtained using the method above
And this is the result using qrcode.make('Some test data').save('test2.png')
Am I missing something? The ImageQt function si a subclass of QImage as far as I understand, in fact I get no runtime errors, but the image is corrupted.
It turns out it takes a couple of steps to do this but you don't need to mess around with intermediate files. Note that the QRcode that qrcode generates is a PIL (python image library but its best to use the fork pillow) object. PIL provides the handy ImageQt module to convert your QR code into an Qimage object. Next you need to use the method QtGui.QPixmap.fromImage to create a pixmap (this method seg faults unless qt's initialisation has been done). The complete code would look something like this:
>>> import qrcode as q
>>> from PyQt4 import QtGui
>>> from PIL import ImageQt
>>> import sys
>>> app = QtGui.QApplication(sys.argv) # line 8 seg faults without this
>>> qrcode = q.make("some test data")
>>> qt_image = ImageQt.ImageQt(qrcode)
>>> pixmap = QtGui.QPixmap.fromImage(qt_image)
Obviously you can neaten that up somewhat but it works.

How can capture a window photo (thumbnail)?

I want to get the photo(thumbnail) of a window which I already have it's handle (hwnd) using python in windows os.
From the link i posted in your question comments, I was able to get a sample working that thumbnails my python interpreter window.
from PIL import ImageGrab, Image
import win32gui
hwnd = 2622054 # My python intepreter window
thumbnailsize = 128, 128
# Set the current window to your window
win32gui.SetForegroundWindow(hwnd)
# Get the size of the window rect.
bbox = win32gui.GetWindowRect(hwnd)
# Grab the image using PIL and thumbnail.
img = ImageGrab.grab(bbox)
img.thumbnail(thumbnailsize, Image.ANTIALIAS)
# Save.
img.save('c:/test/test.png')

videocapture and pyqt

i use this lib http://videocapture.sourceforge.net/ for a capturing web cam. But i don't understand how it video-stream send to qpixmap.
If you check out the documentation for this library, you will see its very short and sweet. http://videocapture.sourceforge.net/html/VideoCapture.html
There are two ways I can tell you that you could get your image into Qt...
The best way - Directly into a QImage
getImage() states that it will return a PIL image. PIL, if you are using the latest version, has a module called ImageQt which can take a PIL Image object and give you back a QImage. From here you could convert that to QPixmap:
from PyQt4 import QtCore, QtGui
from VideoCapture import Device
from PIL import Image, ImageQt
app = QtGui.QApplication([])
cam = Device()
# this is a PIL image
pilImage = cam.getImage()
# this is a QImage
qImage = ImageQt.ImageQt(pilImage)
# this is a QPixmap
qPixmap = QtGui.QPixmap.fromImage(q)
The other way - Write to disk first
If you follow the example they give on this modules website, they show you how to use saveSnapshot() to save the image to disk. This is less desirable than the first method since you have to do disk i/o, but I will still mention it. You would then read it into your Qt app as a QPixmap:
cam = Device()
cam.saveSnapshot('image.jpg')
qPixmap = QtGui.QPixmap('image.jpg')
Do the first method. Its faster and more efficient.

Categories