Is there a way to set a OpenCV window to be always on top?
And can i remove the minimize and close button from my window?
Thank you.
You can use:
cvGetWindowHandle()
to obtain Widows handler. Then using regular windows API you can do anything you like
I found the best solution posted in comments here: Python OpenCV open window on top of other applications
Simply add the command below after opening a window, e.g.
cv2.namedWindow('img_file_name', cv2.WINDOW_NORMAL) # Creates a window
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "python" to true' ''') # To make window active
Use "python" in lower case. Using "Python", as I found in some answers, gave me an error:
21:62: execution error: Finder got an error: Can’t set process "Python" to true. (-10006))
cv2.namedWindow('CCPDA')
cv2.resizeWindow('CCPDA', 200, 200)
hWnd = win32gui.FindWindow(None, 'CCPDA')
win32gui.SetWindowPos(hWnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE | win32con.SWP_NOMOVE)
You can use setWindowProperty
to set an OpenCV window on top with the property WND_PROP_TOPMOST.
This works with OpenCV 3.4.8+ and 4.1.2+.
E.g. in python:
import cv2, numpy as np
window_name = "Top Window"
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
cv2.setWindowProperty(window_name, cv2.WND_PROP_TOPMOST, 1)
cv2.imshow(window_name, np.full((480,640,3), (234,183,39), dtype=np.int8))
cv2.waitKey(0)
The above python code should create a foreground window:
I found that all I needed to do was set my main window to fullscreen then back to normal.
#!/usr/bin/env python
import cv2
import numpy
WindowName="Main View"
view_window = cv2.namedWindow(WindowName,cv2.WINDOW_NORMAL)
# These two lines will force your "Main View" window to be on top with focus.
cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
cv2.setWindowProperty(WindowName,cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_NORMAL)
# The rest of this does not matter. This would be the rest of your program.
# This just shows an image so that you can see that this example works.
img = numpy.zeros((400,400,3), numpy.uint8)
for x in range(0,401,100):
for y in range(0,401,100):
cv2.line(img,(x,0),(0,y),(128,128,254),1)
cv2.line(img,(x,399),(0,y),(254,128,128),1)
cv2.line(img,(399,y),(x,399),(128,254,128),1)
cv2.line(img,(399,y),(x,0),(254,254,254),1)
cv2.imshow(WindowName, img)
cv2.waitKey(0)
cv2.destroyWindow(WindowName)
for me this work fine in macOS, I think that it's will work well in another os
destroyWindow( "windowName" );
namedWindow( "windowName", WINDOW_NORMAL );
moveWindow( "windowName", posx, posy );
imshow( "windowName", frame );
this repeat in loop, the sequence are:
destroy window, this force to create new window
declare new window
move window at position that you want, for example last
position
show window
Related
Intro
I'm building a drawing app using the Streamlit library as a frontend and the Turtle library as the drawing engine.
Issue
Streamlit crashes and throw the following message when the drawing is invoked more than once:
Exception ignored in: <function Image.__del__ at 0x0000017A47EF3558>
Traceback (most recent call last):
File "c:\users\johnsmith\anaconda3\lib\tkinter\__init__.py", line 3507, in __del__
self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread
I want the user to be able to change the inputs and re-run the app as many times as they want without crashes.
Code
Frontend:
# frontend.py
import streamlit as st
from backend import *
st.title("Turtle App")
title = st.text_input("Canvas Title", value="My Canvas")
width = st.number_input("Canvas Width", value=500)
height = st.number_input("Canvas Height", value=500)
length = st.number_input("Square Length", value=200)
clicked = st.button("Paint")
if clicked:
canvas_builder(title, width, height, length)
Backend:
# backend.py
import turtle
def canvas_builder(title, canvas_width, canvas_height, square_length):
CANVAS_COLOR = "red"
PEN_COLOR = "black"
scr = turtle.Screen()
scr.screensize(canvas_width, canvas_height)
scr.title(title)
scr.bgcolor(CANVAS_COLOR)
turtle.setworldcoordinates(0, 0, canvas_width, canvas_height)
t = turtle.Turtle()
t.color(PEN_COLOR)
t.begin_fill()
for i in range(4):
t.forward(square_length)
t.left(90)
t.end_fill()
turtle.done()
Re-production
All the file in the same folder
From Conda's prompt in the same folder, run:
streamlit run ./st.py
Open the app in the browser as indicated by the shell
Press the "Paint" button at the bottom of the UI
Close the Turtle window
Press the "Paint" button again
Check the prompt of the streamlit app for the error
Notes
It seems to be an issue with tkinter processes. I tried to get hold of the root/main one and kill it, but it didn't work.
Ideally, I would like to embed the the Turtle window inside the streamlit app as a plot.
I don't want to replace streamlit and/or turtle.
I solved the problem by running turtle in a child process. New frontend.py code:
import multiprocessing
import streamlit as st
from backend import *
st.title("Turtle App")
title = st.text_input("Canvas Title", value="My Canvas")
width = st.number_input("Canvas Width", value=500)
height = st.number_input("Canvas Height", value=500)
length = st.number_input("Square Length", value=200)
clicked = st.button("Paint")
t = multiprocessing.Process(target=canvas_builder, args=(title, width, height, length,))
if clicked:
t.start()
When I run the Kivy code, the window becomes full screen and how it can get smaller.?
you have fullscreen=1 in your config.ini file
please read https://kivy.org/docs/guide/config.html on where to find config.ini in your platform.
also you can put this in your code ...
Window.fullscreen = 0
First post, yay, I guess. I'm new to Blitz3D, so I'm just now learning how to import a model from 3DS Max into Blitz. Here's the code:
Graphics3D 640,480,32,2
SetBuffer BackBuffer()
camera = CreateCamera()
light = CreateLight()
bottle = LoadMesh("bottle.3DS")
ScaleEntity bottle,0.1,0.1,0.1
End
I put the model file and the code in a folder together, but there's just black when I compile and run the code.
Since ScaleEntity isn't giving you an error, the model does seem to load. However, entities are created at 0, 0, 0 by default, so chances are you just can't see the bottle because your camera is inside it. Try something along the lines of PositionEntity camera, 0, 0, -5 and see if that helps.
Also, if that is your entire code, you're missing a RenderWorld and Flip; either within a loop, or followed by something like WaitKey, so that you can see what's being displayed before your program closes.
Using Octave, I am able to show a image and then plot some red circles over it, as follow:
tux = imread('tux.png');
imshow(tux);
hold on;
plot(100,100,'r','markersize', 10);
plot(150,200,'r','markersize', 10);
The above code display this window:
My question is: How can I save this image as it is being showed inside the window?
Thank you very much!
Pretty simple. Use:
print -djpg image.jpg
print is a command in Octave that allows you to capture what's currently seen in the current figure window. -d specifies what output device you want to write to. There are multiple "devices" you can use to save to file... EPS, PS, TEX, etc. A device can also be an image writer, and so here I chose JPEG. You can choose other valid image formats that are supported by Octave. Take a look at the link I provided above for more details.
After, you just specify what file name you want to save the plot to. In this case, I chose image.jpg.
You can also take a look at saveas. Make sure you get a handle to the current figure first before doing so:
h = gcf;
saveas(h, "image.jpg");
Also... a more point-and-click approach would be to Go to File -> Save As in the figure that your image is displayed in :)
You can use print to save your plot to a file:
print (FILENAME, OPTIONS) // for the current figure
print (H, FILENAME, OPTIONS) // for the figure handle H
and also take a look to saveas
saveas (H, FILENAME)
I am trying to run a very simple program. To open and jpg file and display it using the opencv library for python. Initially it all worked fine but now it just opens a window which doesn't show the image but says 'not responding'. I need to go to the task manager and close it!
from numpy import *
import matplotlib as plt
import cv2
img = cv2.imread('amandapeet.jpg')
print img.shape
cv2.imshow('Amanda', img)
You missed one more line:
cv2.waitKey(0)
Then the window shows the image until you press any key on keyboard. Or you can pass as following:
cv2.waitKey(1000)
cv2.destroyAllWindows()
Here, window shows image for 1000 ms, or 1 second. After that, the window would disappear itself. But in some cases, it won't. So you can forcefully destroy it using cv2.destroyAllWindows()
Please read more tutorials first : http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
None of the answers here worked in MacOS. The following works:
Just add a cv2.waitKey(1) after cv2.destroyAllWindows().
Example:
import cv2
image = cv2.imread('my_image.jpg')
cv2.imshow('HSV image', hsv_image); cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
The solution that worked for me:
Switch from inline graphics to auto. It worked both in Spyder and in Jupyter notebooks.
To change Spyder setting:
Go to Tools > Preferences > IPhyton console > Graphics > Backend: Automatic
(Change backend from Inline to Automatic)
To change Notebook setting:
Enter command:
%matplotlib auto
Some background for my case (for those who may be quick to judge):
It used to work fine: I could open an image, it would load, and it would be responsive (doesn't say "Not responding", can close, focus, etc.) Then I installed some packages and ran some demo notebooks that apparently messed up some settings (Spyder open files were reset too).
I tried adding waitKey(1) (and 0, 30, 1000, etc values too). It made the image load, at least. But the image frame was "Not Responding": didn't refresh, couldn't close, didn't come to top, etc. Had to close using cv2.destroyAllWindows().
Note that everything worked fine during the duration of waitKey. I put this in a loop that shows the same image in the same named window and waits for a few seconds. During the loop everything works fine. As soon as the loop ends, the image window is "Not responding" (which looks like a GUI thread issue). I tried using cv2.startWindowThread(), and didn't make any difference.
Finally, changing from Inline graphics to Auto brought everything back to order.
I've been working with opencv 3.2 and matplotlib too recently and discovered (through trial and error of commenting out lines) that the import of pyplot from matplotlib has some sort of interference with the cv2.imshow() function. I'm not sure why or how it really works but in case anyone searches for this issue and comes across this old forum, this might help. I'm working to try to find a solution around this interference bu
I did also face the same issue. I am running through command line python prompt in centos 7 with the following code
>> import cv2, numpy as np
>> cap=cv2.VideoCapture(0)
>> img=cap.read()
>> cap.release()
>> cv2.imshow('image',img[1])
>> cv2.waitKey(0)
>> cv2.destroyAllWindows()
>> cv2.waitKey(1)
Even then the problem persisted and didn't solve. So I added
>> cv2.imshow('image',img[1])
Adding this did close the image window.Running the command again would create a new instance. Hope you can try if you still face any issues.
The cv2.imshow() function always takes two more functions to load and close the image. These two functions are cv2.waitKey() and cv2.destroyAllWindows(). Inside the cv2.waitKey() function, you can provide any value to close the image and continue with further lines of code.
# First line will provide resizing ability to the window
cv.namedWindow('Amanda', cv.WINDOW_AUTOSIZE)
# Show the image, note that the name of the output window must be same
cv.imshow('Amanda', img)
# T0 load and hold the image
cv.waitKey(0)
# To close the window after the required kill value was provided
cv.destroyAllWindows()
Hoping that you will get the image in a separate window now.
I've installed opencv-contrib-python library instead of opencv-python and now cv2.imshow() function works as expected.
If you have used python notebooks then there is a problem in using cv2.waitKey(0) and cv2.destroyallwindows() in Unix based system to run a program of opencv.
I have an alternative method which would prevent from freezing your image
Steps: -Copy the code from python notebooks and create new filename.py and paste it
- Open terminal
- cd path/to/file
- source activate VirtualEnvironment
- python filename.py
This will run code directly from terminal. Hope this helps you. Example Link: https://youtu.be/8O-FW4Wm10s
I was having this same error until I added the below lines of code. For the waitKey, you can input figures above 0(i.e 1, 100 and above). It serves as the delay time for the window and it is in milliseconds.
----> cv2 waitKey(0)
----> cv2 destroyAllWindows()
I found that i had a breakpoint on the
cv2.waitkey()
funtion. removing that fixed the issue for me
As I tried all solutions mentioned above, it works for displaying an image but in my case, I want to display the video not just the single image in the window, So to solve the problem added
k=cv2.waitkey(10)
if k == 27:
break
after cv2.imshow('title',img)