I am taking some screenshots via adb from my android device (OnePlus 5) to recognize with googles tesseract if there is a specified word inside the page.
Usually it takes 5-8 screenshots with a 1.5 second delay from each other. The first 2-4 screenshots can be opend but then it throws the error and can´t be opend with PIL, Paint.net or on the phone itself.
from adb.client import Client as AdbClient
from PIL import Image
import pytesseract
import os
# The Method with the Problem
# adb package is pure-python-adb
# after 2-4 calls of the method the error ocures
def get_screen(device):
device.shell("screencap -p /sdcard/pgrinder/screen.png")
device.pull("/sdcard/pgrinder/screen.png", "screen.png")
screens = ""
try:
**screens = Image.open('screen.png')**
except Exception:
print("error with image opening")
return -1
return screens
The current error is: OSError: cannot identify image file 'C:\Users\kelle\PycharmProjects\PGrinder\tmp\screen.png'
What fixed the bug for me was to remove the pgrinder directory in this path: /sdcard/pgrinder/screen.png.
I thought it would generate the directory if it doesn´t exist but that wasn´t the case. I don´t no why it worked sometimes and sometimes not. But since I changed it, it worked every time.
Related
I'm a begginer, and I wanted to learn OpenCV in python, so I installed it by PIP
pip install opencv-contrib-python
The first program I made using the libary dosen't worked, it displays an error that was raised by imread() method:
[Errno 2] No such file or directory
I checked a couple of times, and both file and directory exists!
After some time I tried running a diffrent program I made before, that reads files by read() method, and it showed up the same error, it was working before I installed cv2, and i haven't changed it by this time.
Maybe there's something in the code so there are both of these:
import cv2 as cv
img = cv.imread('/Desktop/uczemsiemprogramowacniepaczec/zdjencia/artest.jpg')
cv.imshow('window', img)
cv.waitKey(0)
#this is the first program, it is supposed to show artest.jpg in a diffrent window
the second one:
import keyboard
import time
print("five seconds till spam")
time.sleep(5)
P = open("C:/Users/tymon/Desktop/E/wpisza.txt")
T = P.readlines()
P.close()
for i in T:
keyboard.press_and_release('enter')
time.sleep(1)
keyboard.write(i.replace("\n", ""))
keyboard.press_and_release('enter')
#this was supposed to send an entire wpisza.png file in the chat
Finally, sorry for possible bad english (it is not my native language)
I searched for the solution to this problem everywhere on the Internet, and I haven't found any, so I hope someone knows this...
Okay, so first, I would check the path again, maybe left click on your image, see properties and check the path there. Also, try to use relative paths. Your path is always FROM your file. So if your path is /Project/main.py and your image is in /Project/test_images/t1.jpeg your code will be:
import cv2 as cv
img = cv.imread('./test_images/t1.jpeg')
cv.imshow('window', img)
cv.waitKey(0)
I've been trying to write a little screenshot script for arch. It works, but the problem is when I try to assign it a keybinding in my i3-config it does nothing.
First I tried writing it fully in bash which worked fine but I stumbled onto the same problem with it not executing.
So I have redirected the output to a log-file to check it out and it welcomes me with this:
import: unable to grab mouse '': Datei oder Verzeichnis nicht gefunden # error/xwindow.c/XSelectWindow/9306.
import: unable to read X window image '': Erfolg # error/xwindow.c/XImportImage/4942.
import: unable to read X window image '': Erfolg # error/xwindow.c/XImportImage/5049.
import: `/home/lukas/Screenshot/20190419/scoot7.png' # error/import.c/ImportImageCommand/1288.
Translation first line: Couldn't find file or directory # error[...]
Translation Erfolg: success
I've tried googling it, which didn't lead me to anything really and I didn't really find any path resembling error/xwindow.c and so on.
Here is my code:
#!/usr/bin/env python
import os, os.path
import datetime
import sys
d = datetime.datetime.today()
directory="/home/lukas/Screenshot/%s"%d.strftime('%Y%m%d')
if not os.path.exists(directory):
os.mkdir(directory)
fileCount = 1
for file in os.listdir(directory):
if file.endswith('.png'):
fileCount+=1
filename = "%s/scr%d.png"%(directory,fileCount)
os.system("import %s"%filename)
and here is my entry to my i3 config:
bindsym $mod+Shift+F12 exec --no-startup-id scoot > /tmp/log.out 2>&1
The expected outcome of this is that when I press mod+shift+f12 it should transform my mouse-pointer to a "crosshair" so I can select something and takes a screenshot of that.
The actual result is that if I run it normaly it works, but if I try to use the Keyboard-Shortcut it just does nothing but output to my logfile.
I am pretty much a newbie to programming and linux, and I have no idea why it cannot find my mouse and I wanted to know if I can explicitly tell the program to use it or if there is another way to do this.
Thanks alot.
Hugenotte
I wrote a bash script a little while ago to do exactly what you are trying to do, using the very common utility ImageMagick that you can find here on Arch.
Here it is in case you are open to this alternative:
#!/bin/bash
# take screenshot using import from imagemagick
# allows to select the area by dragging across a rectangle
# or to select entire window by clicking inside it
set -e
# the date and time will be used as the file name
time=$(date +"%F_%H:%M:%S")
# naming the urxvt window "screenshot" so that the i3 "no_focus" option gets applied to it
urxvt -title "screenshot" -e bash -c "import $HOME/Screenshot/$time.png"
I then use it in i3 with:
no_focus [title="screenshot"]
bindsym $mod+Shift+F12 layout tabbed; exec --no-startup-id bash my_script.sh
Of course, you may want to change the date format to what you had in python. I like having the time in case I take several screenshots in a row. And you have to replace urxvt with the name of your terminal emulator and you might have to adapt the -title flag if your terminal emulator doesn't give windows a name in this way.
Note that naming the window is important: it took me a little while to figure out how to go around what happens without naming the window and using the no_focus on that window in i3:
The focus would jump to the screen capture window and thus out of the window of which I wanted to take a screenshot. It might be possible that the issue you are facing with your bash and python scripts may be related to this. You have to force i3 to keep your mouse on the old window and not jump to the screen capture window triggered by the script (by default, i3 will focus on a newly created window).
I'm using pyautogui to click on a button that periodically pops up on my GUI as shown in the script below. However when the button is not on the screen, the script makes two annoying beep sounds while going through the loop.
If I replace pyautogui.locateOnScreen(...) with None, which seems to be the return value if the image can't be located on the screen, the sound seems to disappear.
The script runs in a Jupyter Notebook (v4) using python 2.7 and I'm on Debian 8.1 with Gnome.
import pyautogui
import time
starttime = time.time()
while time.time()-starttime<10:
img_path_inactive = "/home/user/folder/inactive_target.png"
img_path_active = "/home/user/folder/active_target.png"
img_list = [img_path_inactive, img_path_active]
get_target = map(pyautogui.locateOnScreen, img_list) # <--- This line beeps! See edit 2
if any(get_target):
pyautogui.click(filter(None, get_target)[0][0], filter(None, get_target)[0][1])
# The if check above was previously (hence the title):
# if pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive):
# click_target = pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive)
# pyautogui.click(click_target[0], click_target[1])
time.sleep(2)
print("Finished loop.")
Edit
I put the script in a .py file and ran it from the command line to check if it is a jupyter thing. It still beeped though.
Afterwards I ran pyautogui.locateOnScreen against three images, which caused predictably three beeps... So it definitely seems to be a pyautogui issue/'feature'...
Edit 2
pyautogui.locateOnScreen is imported from here, see line 238. It actually does seem to raise an exception:
except ImageNotFoundException:
if time.time() - start > minSearchTime:
raise
I'm also on GNU/Linux and experiencing beeping when the pyautogui.locateOnScreen() function runs (whether or not it locates the image).
I found that scrot is the culprit. The solution:
$ sudo mv /usr/bin/scrot /usr/bin/scrot-noisy
Create /usr/bin/scrot with these contents:
#!/bin/bash
scrot-noisy --silent "$#"
$ sudo chmod a+x /usr/bin/scrot
Ok, I found a workaround to the beeping.
After going to the source of the module from which pyautogui.locateOnScreen is imported, I believe that the function raises a custom ImageNotFoundException somewhere down the track. I didn't fully debug it though.
Being on Gnome, all Exceptions are announced by an annoying beep.
The workaround that did it for me was to turn off the system beep altogether.
I added the following line to ~/.xsession:
xset b off
which killed the beep.
Here is my python program:
#!/usr/bin/env/ python
import cv
capture1=cv.CaptureFromCAM(0)
cv.SetCaptureProperty(capture1,cv.CV_CAP_PROPER_FRAME_WIDTH,320)
cv.SetCaptureProperty(capture1,cv.CV_CAP_PROPER_FRAME_HEIGHT,240)
while 1:
cam1=cv.QueryFrame(capture1);
cv.SaveImage("camera.jpg",cam1);
cv.WaitKey(11)
print 'Done!'
On crontab:
#reboot sudo python /home/program.py >/home/result.txt
But its not saving the image.Definitely I have done something wrong! I got the similar problem when I was reading image cv2.imread("image.jpg") but it was returning None so I added full path to the image /home/image.jpg.That problem was solved!.Is cron not getting camera feed?
Thanx for help!
First and foremost, make sure the application succeeds communicating with the camera:
import cv
capture1 = cv.CaptureFromCAM(0)
if not capture1 :
print "!!! Failed to open a camera interface"
# Ideally, exit the application.
cv.SetCaptureProperty(capture1,cv.CV_CAP_PROPER_FRAME_WIDTH,320)
cv.SetCaptureProperty(capture1,cv.CV_CAP_PROPER_FRAME_HEIGHT,240)
Remember to test if the frame was successfully retrieved from the camera:
while 1:
frame = cv.QueryFrame(capture1);
if not frame:
print "!!! Failed to retrieve frame"
break
# Right now, your code overwrites the same file at every iteration of the loop.
# It might be better to add a BREAK at the end for testing purposes.
cv.SaveImage("camera.jpg", frame);
# There's no need to call WaitKey() if the image is not displayed on a window.
#cv.WaitKey(11)
print 'Done!'
SaveImage() will fail when the application doesn't have permission to write files in the directory from where it was executed. Since crontab is responsible to call your application, I imagine that it does that from a directory where the user doesn't have the right permissions. If this is the case, I strongly suggest you to feed SaveImage() with the full path to the file.
The problem was in cv.ShowImage or cv2.imshow.When I commented this line everything worked fine! Previously the program got stuck at this this line.(while execution through cron).[That I was writing in my original program]
Hello everyone I'm trying to open a image that i have downloaded through a link. I searched on the site and found something very useful and implemented that into my code.
*if* __name__ == "__main__":
import urllib
droste = urllib.urlopen("http://is.gd/cHqT")
with open("droste.png", "wb") as imgFile:
imgFile.write(droste.read())
print "Got it!"
droste = Image.open("droste.png")
while droste:
droste.show()
droste = reveal(droste)
if droste:
open("droste.png", "wb").write(droste)
droste = Image.open("droste.png")
The error occurs on the 7th line "droste = Image.open("droste.png")". I'm getting a IOError: cannot identify image file. I know the image has been downloaded because the codes runs great until that particular line and the line print "Got it!" actually confirms that its been downloaded. I don't know if I need to specify the path of the image file in the parameter in the open instead the of image name. Or maybe I need to check the path of the file. Please help.
Your code is functional. The problem is how you are running it. You mentioned in your comments that you are using PythonAnywhere. PythonAnywhere is not set up to do anything graphical. It will download the image into the correct directory, but PIL will not function correctly with PythonAnywhere.
Try the following code to test this.
import urllib
if __name__ == "__main__":
droste = urllib.urlopen("http://is.gd/cHqT")
with open("droste.png", "wb") as imgFile:
imgFile.write(droste.read())
print "Got it!"
print "Now lets test if it really exists..."
try:
with open("droste.png", "rb") as imgFile:
pass
print "There were no errors so the file exists"
except:
print "ERROR: image was not saved properly!"
If you start up a BASH session with PythonAnywhere, you will see that the file droste.png exists, and you can download it to your computer and view it. Your program is OK.
If you really want to use your program, or get serious about python programming. You really should install Python locally to your computer. If you want to keep your code in the cloud, then use dropbox, github, or bitbucket. PythonAnywhere has uses, but normally you will just want to have python on your computer.