File reading problem after installing cv2 [Python] - python

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)

Related

Sometimes the screenshot image via adb can not be opend

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.

Why does my if in a loop make a beep

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.

IDLE subprocess startup error

I have the code below in a file called code.py. I am using IDLE to edit the file. When I click Run>Run Module I get the error:
"IDLE's subprocess didn't make connection. Either IDLE can't start a
subprocess of personal firewall software is blocking the connection."
I am using Windows 7 Ultimate 64bit, but I have the 32bit version of Python 2.7 installed.
I have looked for a solution on this site as well as others but all of them seem to recommend deleting something called tkinter.py (I have no idea what this is) or to turn off my firewalls (I have none enabled aside from Microsoft Security Essentials which isn't a firewall.)
#Globals
#-------------------
x_pad = 476
y_pad = 444
import ImageGrab
import os
import time
import win32api, win32con
def screenGrab():
box = (x_pad+1,y_pad+1,x_pad+641,y_pad+480)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) +
'.png', 'PNG')
def main():
pass
if __name__ == '__main__':
main()
def leftClick():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print 'Click.' #completely optional. But nice for debugging purposes.
def leftDown():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
print 'left Down'
def leftUp():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
time.sleep(.1)
print 'left release'
def mousePos(cord):
win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])
def get_cords():
x,y = win32api.GetCursorPos()
x = x - x_pad
y = y - y_pad
print x,y
The thing is "python.exe" is being obstructed by "tkinter.py") that you created(i.e., you have written a program with Tk() and named it as tkinter.py and saved that in the root folder of python). And that's it just make sure that you don't save any program file directly in the root folder of python.
Another fix!!! Hopefully this will help someone.
I had the same problem and noticed something quite interesting. I had accidentally named a file (inside the desktop folder I was working in) "tkinter" (it will cause the same problem if you rename a file by any reserved keyword, I assume). Everytime I ran or attempted to run this file, it created a pycache folder, and the error you mention above came up. Deleting the erroneously named python file solved the problem.
So - look for ANY files (in the folder you are working with or indeed the root folder) that are named after any reserved words. Delete them. Hopefully it'll work!
I had the same problem. what i did that solved it, was to move every .py file that i had created in "C:\Python33" folder, to a sub-folder that i named "Examples". seems like one of my files was the cause of this problem.
I also had the following problem. My file was named code.py, and was working fine untill I installed Canopy, and numpy.
I tried reinstalling python, but what solved the problem for me was simply renaming the file. I called my file myCode.py, everything started working fine. Strange problem...
I made a python file and named it "socket.py" so then python IDLE showing an error on startup that 'startup failure'
so the problem is that if we are using python reserved keywords or module names as our python file name that it conflicts with built-in modules.
the solution is: go to path C:\Users\sony\AppData\Local\Programs\Python\Python38 where your python files are saved and just renamed that file.
then start IDLE.
Happily using IDLE continously under python36 and windows10, it has suddenly given this error on all the programs I'm working on, with no new files created.
I terminated IDLE and tried to restart it with idle.bat but that no longer works.
Happily I have been able to restart it successfully with Lib\idlelib\idle.pyw.
All my recent programs are there and they can again be run without problems.
No need to reinstall python.

Crontab camera capture using python-opencv

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]

Open Image Error Python

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.

Categories

Resources