OpenCV destroyallWindow function should not work? - python-3.x

import cv2
img = cv2.imread('lena.jpg', -1)
cv2.imshow('image', img)
k = cv2.waitKey(0) & 0xFF
if k == 27:
cv2.destroyAllWindows()
elif k == ord('s'):
cv2.imwrite('lena_copy.png', img)
I am a beginner in OpenCV. As I was playing around with the functions, I noticed this error. This script, if I understand correctly should first show the image, then will either get destroyed or saved depending on if I press the escape key or s key. But the thing is no matter what key I pressed, the window gets destroyed. It's like I don't need the destroyAllWindows() function to destroy all my window, All I need is to press a random key. Is it because I misunderstand the purpose of destroyAllWindows() function or is it because of something else?

When you press the escape key, it will explicitly call destroyAllWindows. When you press s, it will first save the image and then the operating system will destroy all windows upon exit. If you press any other key, again, the OS will close and deallocate all windows upon exit.
From OpenCV docs:
You can call destroyWindow() or destroyAllWindows() to close the
window and de-allocate any associated memory usage. For a simple
program, you do not really have to call these functions because all
the resources and windows of the application are closed automatically
by the operating system upon exit.

The problem is with waitKey not destroyAllWindow. The latter works fine and does what it should do.
You must understand that when you display a window, (by imshow()) your application must have main events loop, in which all events related to interactions with the windows like clicking, resizing, moving, displaying etc. are processed. This main loop of GUI application is created and processed in waitKey() function invocation.
Your current flow is as follows:
show window
press any key
all windows are closed no matter what key was pressed because you didn't call waitKey again for k == 's'
.
if k == 27:
cv2.destroyAllWindows()
elif k == ord('s'):
cv2.imwrite('lena_copy.png', img)
cv2.waitKey(0)
by adding the last line, you start new events loop, and windows are still visible.

Related

how to switch between windows in linux with command

I was studying about "AutoKey" and I understood that it interprets the keys as a button and create scripts..
image "AutoKey"
I'm using
"window.activate('Google Chrome')"
however it switches only to google chrome. How do you switch between two programs when you press a key?
Example:
"window.activate('Google Chrome')" - I'm on chrome
"window.activate('explorer.exe')" - I'm in the archive folder
I want them to toggle when I press a key
bar fedora
If you want them to toggle, then you have to find out where you are to start with. Start your script by getting the the window title...
NOTE: The following is untested code.
If it doesn't work and you can't easily figure out why, post on Gitter and we'll figure it out. The script below will fail as written because I don't think you can have empty except: clauses. The least you can do is add a pass statement to each of them so the error is ignored and doesn't throw an exception.
I assume that your window title strings are correct although explorer.exe gives me pause because I'm not sure that will run on Linux and AutoKey is a Linux X11 application. It does not work on Wayland or on Windows.
win = window.get_active_title()
if win == 'Google Chrome' :
try:
window.activate('explorer.exe')
except:
## do something if that didn't work
elif win == 'explorer.exe'
try:
window.activate('Google Chrome')
except:
## do something if that didn't work
else
## do something when neither is the active window
If one or both of those windows/apps aren't running when this script is launched, then something will fail. You can either try to launch them or do something else depending on your requirements.
I don't think the first API call can fail, but you can put that in a try: block too if necessary.
Also, when things look right, but still don't work, the first thing to try is to add long delays before/between all the API calls with something like time.sleep(1). Once the script works, you can reduce or eliminate the delays one at a time.

How to Create a Cursor or Loading Indicator for an Infinite Loop

I am scraping current follow requests from Instagram. I have a main infinite loop that it making the requests and prints OK when it is done. I want to display an animated cursor or loading progress while it is downloading names.
while 1:
response = requests.get(IG_CFR_PAGE, headers=headers(""), params=params, cookies=cookies)
if response.status_code == 200:
cfr = response.json()
for entry in cfr["data"]["data"]:
#print(entry["text"])
usernames.append(entry["text"])
if cfr["data"]["cursor"]!= None:
params['cursor'] = cfr["data"]["cursor"]
time.sleep(1)
else:
break
else:
print(response.status_code)
print("Error in request .... aborting")
break
print("ok")
I looked for tqdm but it takes an iterable. In my case, I am just looping over JSON keys in line for entry in cfr["data"]["data"]: and so I guess can't use it. I just need suggestions as to know what should I use to indicate that this script is actually doing something. I just need suggestions or pseudocode is fine to send me in a right direction... the actual programming code is not needed as I will do that myself.
Thank you
As far as I'm aware, most functions that allow you to change the mouse cursor in Python are available only from various GUI modules - most of the popular ones, such as tkinter, PyQt5, pygame or others.
The problem is that most of these may only work when you've created a window of the GUI, which is probably unnecessary or not a nice idea if you're not using the same GUI, or any GUI for that matter. Even then, some may only take effect when the mouse pointer hovers over a certain widget in that GUI.
Note:
I've only (unsuccessfully) tried doing this with pygame.cursors before. It may be convenient because it even lets you create a custom shape with strings, or use a system cursor. But it displays a pygame.error: video system not initialized if you try doing this without having called pygame.display.init() first. I tried creating a window and setting a cursor, but it didn't seem to take effect.
After a quick google search for other ways to set an animated cursor, I came across this SO answer which might offer some insight if you're on windows.
Overall, using a terminal animation may probably be better and easier, so
this is an attempt at a basic answer for a loading animation in a terminal window :
(Of course, for an indefinite length of loop, it doesn't make sense to store a percentage completion etc, so this just animates at an arbitrary pace and repeats when it reaches the end)
i, w, d = 0, 20, 10000
while True:
# Do whatever
# No print statements except this last one
i = (i+1)%(w*d)
l = i//d
print("\r Processing... |" + " "*l+ "█" + " "*(w-l-1) +"|", end='')
i is used for iteration, w is the length of the bar, and d used to create some sort of 'delay', so that the bar doesn't change at every single iteration, but some slower (visible) speed
Edit: Important Note: The '\r' that resets the cursor position doesn't work in every terminal - it may still move to a new line for the next print() instead of the start of the same line - but this should most likely be fine in your system Terminal/cmd etc... May not be a good idea to run this in IDLE :P
Edit 2: Based on your comment, for a blinking indicator (using the same approach) -
i, d = 0, 300000
while True:
i = (i+1)%d
print("\r Working... " + ("█" if i < d/2 else " "), end='')

How to use get keyboard input using Mac? (Python3)

I want to try and get a keyboard input and use it in a conditional statement; such as if 'a' is pressed do function, if 'b' is pressed do function b. The problem is, whenever I get keyboard output, this error gets displayed. raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator. I looked at some other posts, but I couldn't find a working solution. [Btw I am using the keyboard module (But it makes the error pop up), If there are any better solutions please tell].
Il put a code example I found:
import keyboard
keyboard.write("GEEKS FOR GEEKS\n")
keyboard.press_and_release('shift + r, shift + k, \n')
keyboard.press_and_release('R, K')
keyboard.wait('Ctrl')
Note: I don't know how to get it to run, also if there is any problems in it, please tell a viable solution. Thanks!

Keeping track of current input before user presses enter

I'm using Python's cmd module to handle a terminal input loop.
I have a thread running in the background, which prints out some stuff in the terminal when it receives a message. These messages break the visual user input:
> writing a com
### message generated from a thread and printing during user input ###
mand
I ask a related question here and was basically told that one way to avoid breaking the user's input would be to keep track of user input, so that when a message comes in I can print the message and the reprint the user input. When I asked that question I wasn't using the cmd module.
When using the cmd module, how would I keep track of what the user has currently typed, so that I can reprint it after?
I discovered the readline module and it's get_line_buffer() method.
Here's how I solved it, in the thread that wants to print out data while I'm reading user input in the main:
import readline
# Save the current buffer
current_buffer = readline.get_line_buffer()
# Print our stuff, note the \r is important to overwrite the current buffer
print("\rladida interruption\nsome more interruption\n")
# Reprint our buffer
print('> ' + current_buffer, end='', flush=True)
Here's an example, before:
$ ./main.py
> help
and after:
$ ./main.py
ladida interruption
some more interruption
> help
Note how the command prompt cleanly moved down, with the users current command input in place. The cursor is also in the right position to continue typing, backspace works fine too.

QClipboard works funny under GNU/Linux

#!/usr/bin/python
from PyQt4.QtGui import QApplication, QClipboard
import sys
app = QApplication(sys.argv)
QApplication.clipboard().setText('yo', mode=QClipboard.Clipboard)
input() #wait for input
When I set mode=QClipboard.Clipboard (the default one), it doesn't work. It leaves old data in the clipboard and in the selection clipboard.
When I change it to mode=QClipboard.Selection (the one specific to X), it replaces both selection and primary clipboard with yo.
Question: why the "main thing" (mode defaults to QClipboard.Clipboard after all) doesn't work, while something that should work only conditionally (QClipboard.supportsSelection()) does the job? How can I make this work properly?
I can't actually reproduce the problem on my Linux system: it all works fine for me.
However, the docs say that the clipboard needs an event-loop on X11:
the X11 clipboard is event driven, i.e. the clipboard will not
function properly if the event loop is not running. Similarly, it is
recommended that the contents of the clipboard are stored or retrieved
in direct response to user-input events, e.g. mouse button or key
presses and releases. You should not store or retrieve the clipboard
contents in response to timer or non-user-input events.
So you might be able get your example working on your system by forcing the processing of queued events like this:
app.clipboard().setText('yo')
app.processEvents()
input()
Obviously that is a contrived "solution", though, and the correct way to do things is to start the event-loop and follow the advice in the docs.

Resources