import pyautogui
button7location = pyautogui.locateOnScreen('picturee.png')
print("finished")
The picture works perfect in a HTML file i created.
Digging into the source code, we are directed from pyautogui to pyscreeze where we can see the following block of code in the location functions.
if isinstance(needleImage, (str, unicode)):
# 'image' is a filename, load the Image object
needleFileObj = open(needleImage, 'rb')
needleImage = Image.open(needleFileObj)
In short, you need the image to be in the same directory as the one you're launching the script from.
Link to source
Related
This is the code immediately before I get stuck:
#Start a new post
driver.find_element_by_xpath("//span[normalize-space()='Start a post']").click()
time.sleep(2)
driver.find_element_by_xpath("//li-icon[#type='image-icon']//*[name()='svg']").click()
time.sleep(2)
The above code works well. The next step though has me puzzled.
I would like to upload the latest image file from my downloads folder. When I click on the link above in LinkedIn it navigates to my user folder (Melissa). (see image)
So... I'm looking for the next lines of code to navigate from the default folder to the Downloads folder (C:\Users\Melissa\Downloads), then, select the newest file, then click 'open' so it attaches to the LinkedIn post.
You can upload the image using this method:
import getpass, glob, os
# Replace this with the code to get the upload input tag
upload_button = driver.find_element_by_xpath("//input[#type='file']")
# Get downloads
downloads = glob.glob("C:\\Users\\{}\\Downloads\\*".format(getpass.getuser()))
# Find the latest downloaded file
latest_download = max(downloads, key=os.path.getctime)
# Enter it into the upload input tag
upload_button.send_keys(latest_download)
I can do this OK both in js and php but not in python. I'm trying to pull a thumbnail image from google books api into a python variable.
The text objects are fine eg
newTitle = (parsed_json['items'][0]['volumeInfo']['title'])
isbn10 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][1]['identifier'])
isbn13 = (parsed_json['items'][0]['volumeInfo']['industryIdentifiers'][0]['identifier'])
The image is supplied in the api as follows. (if you put the http// url into a browser you see the image):
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
I have tried the simple:
myImage = (parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work.
I have installed pillow to provide image management:
from PIL import Image
img = Image.open("parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail]") or
img = Image.open(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
which doesn't work. I have tried more complex arrangements:
from PIL import Image
import requests
from io import BytesIO
response = requests.get(parsed_json['items'][0]['volumeInfo']['imageLinks'][thumbnail])
img = Image.open(BytesIO(response.content))
but nothing seems to work. I have tried many other variations on these attempts. I have also, unsuccessfully tried to load the text that points to the thumbnail to try another route. I am confident that the "['items'][0]['volumeInfo']['imageLinks'][thumbnail]" is correct though my only way of testing whether the variable is properly loaded is to save it or if the line of code isn't working.
I didn't have problems downloading and opening the image.
I have use the following code
import requests
from PIL import Image
image_url = "https://books.google.com/books/content?id=XUnNDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api"
r = requests.get(image_url)
with open("demo_image",'wb') as f:
f.write(r.content)
img = Image.open("demo_image")
I am new to Python. I am attempting to create a Python OCR program, and am following a tutorial online for it. Here is the recommended code I use:
from PIL import Image
from pytesser import *
image_file = 'menu.tif'
im = Image.open(image_file)
text = image_to_string(im)
text = image_file_to_string(image_file)
text = image_file_to_string(image_file, graceful_errors=True)
print "=====output=======\n"
print text
The tutorial link is found here. I am getting this error when running this code however.
from pytesser import *
ImportError: No module named 'pytesser'
I have followed the instructions, from installing OCR here and the PyTesser library here code(dot)google(dot)com/archive/p/pytesser/downloads (sorry because <10 rep i can't post more than 2 links).
This (see gyazo below) is a screenshot of my installation files so far, where "pytesser_v0.0.1" is my pytesser folder, "tesseract-master" was found on GitHub (probably not relevant), and "tessinstall" is the folder where I installed tesseract and finally pyimgr.py is my file I am attempting to run.
gyazo(dot)com/333f8a3333e87895558f26875a8a8487
I was also previously getting an error regarding PIL import Image. I should not be using PIL, so is there any other way I can import Image without PIL? maybe pillow?
My Python version is 3.5.2 and I am using windows 10.
My first hunch is that your library is installed in a place that Python does not know.
import sys
print sys.path
If you execute those lines in Python it will show you where Python will look for eggs. Is the pytesser lib there?
Furthermore: As a side note:
pip3 search tesseract will show you some other tesseract Python packages. So you can use the Python package manager.
Change the code to this:
"""OCR in Python using the Tesseract engine from Google
http://code.google.com/p/pytesser/
by Michael J.T. O'Kelly
V 0.0.1, 3/10/07"""
import PIL.Image
import subprocess
import util
import errors
tesseract_exe_name = 'tesseract' # Name of executable to be called at command line
scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format
scratch_text_name_root = "temp" # Leave out the .txt extension
cleanup_scratch_flag = True # Temporary files cleaned up after OCR operation
def call_tesseract(input_filename, output_filename):
"""Calls external tesseract.exe on input file (restrictions on types),
outputting output_filename+'txt'"""
args = [tesseract_exe_name, input_filename, output_filename]
proc = subprocess.Popen(args)
retcode = proc.wait()
if retcode!=0:
errors.check_for_errors()
def image_to_string(im, cleanup = cleanup_scratch_flag):
"""Converts im to file, applies tesseract, and fetches resulting text.
If cleanup=True, delete scratch files after operation."""
try:
util.image_to_scratch(im, scratch_image_name)
call_tesseract(scratch_image_name, scratch_text_name_root)
text = util.retrieve_text(scratch_text_name_root)
finally:
if cleanup:
util.perform_cleanup(scratch_image_name, scratch_text_name_root)
return text
def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True):
"""Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
converts to compatible format and then applies tesseract. Fetches resulting text.
If cleanup=True, delete scratch files after operation."""
try:
try:
call_tesseract(filename, scratch_text_name_root)
text = util.retrieve_text(scratch_text_name_root)
except errors.Tesser_General_Exception:
if graceful_errors:
im = PIL.Image.open(filename)
text = image_to_string(im, cleanup)
else:
raise
finally:
if cleanup:
util.perform_cleanup(scratch_image_name, scratch_text_name_root)
return text
if __name__=='__main__':
im = PIL.Image.open('phototest.tif')
text = image_to_string(im)
print text
try:
text = image_file_to_string('fnord.tif', graceful_errors=False)
except errors.Tesser_General_Exception, value:
print "fnord.tif is incompatible filetype. Try graceful_errors=True"
print value
text = image_file_to_string('fnord.tif', graceful_errors=True)
print "fnord.tif contents:", text
text = image_file_to_string('fonts_test.png', graceful_errors=True)
print text
url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg"
I am trying this:
import urllib
url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg"
IMAGE=url.rsplit("/")[-1]
urllib.urlretrieve(url,IMAGE)
Image is downloaded in the destination folder after the execution, but it is corrupt.
"Could not load image"; error pops up.
It might be because the domain that you are trying to reach has restrictions over download policy. Check this one out, hope it helps! https://stackoverflow.com/a/8389368/2539771
import urllib
URL = "https://images-na.ssl-images-amazon.com/images/I/714tx9QbaKL.SL1500.jpg"
urllib.urlretrieve(URL, "sample.png")
from PIL import Image
img = Image.open('/home/sks/sample.png')
img.show()
I've been attempting to work at this for hours but decided to turn to the experts here on stackoverflow.
I'm trying to download an image from a url:
import urllib
originalphoto = urllib.urlretrieve(bundle.obj.url)
#originalphoto is being saved to the tmp directory in Ubuntu
This works and it saves the image in the tmp directory, but I need to modify this image by resizing it to a 250px by 250px image and then save it to a folder on my Desktop: /home/ubuntu/Desktop/resizedshots
The name of the original image is in bundle.obj.url, for example if bundle.obj.url is:
http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg the name of the image is "09-09-201315-47-571378756077.jpg"
After the image is resized, I need to save is to this folder as 09-09-201315-47-571378756077small.jpg
As you can see, I'm adding in the word "small" to the end the file name. Once all of this is done, I would like to delete the temporary image file that was downloaded so that it doesn't take up the disk.
Any ideas on how this can be done?
Thanks
This is the definition:
def urlretrieve(url, filename=None, reporthook=None, data=None):
You can set the second argument to something you know and then do
import os
os.remove(something_you_know)
If you do not set the second argument you do this:
import urllib, os
url = 'http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg'
file, headers = urllib.urlretrieve(url)
# do something
os.remove(file)
if os.remove does not work you still have the file open.