This is my Program, Text Extraction from Image program:
import pytesseract
from PIL import Image
import os
from os.path import join
import sys
con_1 = True
store_1 = []
store_2 = []
store_3 = []
con_1 = True
print("Welcome to my Text Extraction from Image Program. Here you can extract text from any image.")
while con_1:
image_name = input("Enter your image's name:")
for root, dirs, files in os.walk("/home/"):
if image_name in files:
found = join(root, image_name)
store_1.append(found)
if len(store_1) == 0:
ask_1 = str(input("Your image was not found. Do you want to try again(Y/n)?:"))
if ask_1 == "Y" or ask_1 == "y":
con_1 = True
elif ask_1 == "N" or ask_1 == "n":
con_1 = False
else:
print("Your input is out of bounds. Please try again.")
else:
print("Your image was successfully found.")
image_open = Image.open(found)
image_text = pytesseract.image_to_string(image_open)
print(image_text)
break
This is the image I am testing it on:
And this is the most weirdest output I have ever seen:
‘Understanding how computer memory
ia tire terrae tec
programming lan
This is another image I am testing it on:
And another really weird output:
Sesh chee nia ec Hiok pc
RU hun oe
mete een
machines work while still being easy to learn.
I have never seen my program giving me such off-target and weird outputs. I have absolutely no idea how this is happening. I would very much like to know how to fix it as well as why my program is malfunctioning.
Related
I am trying to improve a code I found online so that it doesn't waste so much paper.
The files I will be printing are small labels which do not take a lot of space. I would like to be able to "merge" those labels so that they'd be printed out by groups of 6 per page.
This is the code (it already has some modifications):
# Import libraries
import os
from pickle import TRUE
import time
import tkinter as tk
from tkinter import filedialog
def menu():
print("1- Retry")
print("0- Exit")
s=TRUE
while s:
opt = input("Select an option: ")
try:
if int(opt) == 1 or int(opt) == 0:
opt = int(opt)
s = False
except:
input("Press enter to try again.")
return opt
s = TRUE
while s:
root = tk.Tk()
root.withdraw()
path = filedialog.askdirectory()
try:
# Extracting all the contents in the directory corresponding to path
l_files = os.listdir(path)
# Iterating over all the files
for file in l_files:
# Instantiating the path of the file
file_path = f'{path}\\{file}'
# Checking whether the given file is a directory or not
if os.path.isfile(file_path):
try:
# Printing the file pertaining to file_path
os.startfile(file_path, 'print')
print(f'Printing {file}')
# Sleeping the program for 5 seconds so as to account the
# steady processing of the print operation.
time.sleep(5)
except:
# Catching if any error occurs and alerting the user
print(f'ALERT: {file} could not be printed! Please check\
the associated softwares, or the file type.')
else:
print(f'ALERT: {file} is not a file, so can not be printed!')
s = False
except:
print('No folder selected.')
opt = menu()
if opt == 0:
break
else:
pass
print('Task finished!')
I have seen this post for Ubuntu 20.04 and Pillow version 9.0.0 but the problem now exists on my Windows machine running Python 3.9.12 locally. What is weird is that it has worked fine the last two weeks and decided today to delete a temporary photo immediately after displaying it to me and therefore blocking me from seeing it.
My code is as follows though I believe it does not matter
if file[file.index('.')+1:] == "jpg" or file[file.index('.')+1:] == "png": #only jpg and png files
totalImages += 1
img = Image.open(str(pathArg2) + '/' + file) #opens the image
exif_date = img.getexif().get(306) #gets the date from the exif data
if exif_date != None:
for coord in locations:
for time in coord.time:
if exif_date[0:15] == time[0:15]: #if the creation time of the image up to a 10 minute interval is the same as the time of the location
address = locator.reverse(coord.coords).address #gets the address of the location
image_editable = ImageDraw.Draw(img)
image_editable.text((15,15), address, fill = (170, 255, 0), font = ImageFont.truetype("arial.ttf", int((img.width*img.height) ** (1./4.)))) #adds the address text to the image
img.show()
print("Was the address correct? (y/n)")
answer = input("> ")
while answer != "y" and answer != "n": #checks if the address is correct with the user
answer = input("> ")
if answer == "y":
imagesCorrectlyAnnotated += 1
img.close()
return True
else:
imagesIncorrectlyAnnotated += 1
img.close()
img = Image.open(str(pathArg2) + '/' + file)
imagesAnnotated += 1
time.sleep() does not do anything either but that is what I thought would be the case
Commenting out code below img.show() does not change the behavior.
If I run even a simple python program to show an image such as
from PIL import Image
import time
img = Image.open('TestImages/20211203_175356.jpg')
img.show()
time.sleep(30)
It still shows and then immediately removes the images and says its been deleted, even if the program is still running
I made a program that's supposed to record people in my household talking for 1 minute. I think my code has successfully (though messily) been able to save the *.wav file and classifying the recording on gender. The male recordings are supposed to be saved in the male_voices folder and the female recording are supposed to be saved in the female_voices folder.
My question is: I have searched and couldn't seem to find a way to save these recordings to a specific file path. As you can see I tried using
os.join(path, "son.wav")
but it doesn't work.
My code is as follows:
# import required libraries
import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
import os
male_members ={'s':'son', 'b':'brother', 'u':'uncle', 'f':'father', 'n':'nephew', 'mc':'male cousin', 'o':'other'}
female_members ={'d':'daughter', 's':'sister', 'a':'aunt', 'm':'mother', 'n':'niece', 'fc':'female cousin', 'o':'other'}
# Sampling frequency
freq = 44100
# Recording duration
duration = 60
while True:
user = str(input("Do you want to record a female [f] or male [m] voice or exit[e]? "))
if user.lower() == 'm':
path = r"C:\Users\core i5\Desktop\GitHub\DataSci\Data Analysis and Tools\Dataset\male_voices"
male = str(input("Are you recording your son[s], brother[b], uncle[u], father[f], nephew[n], male cousin[mc], or other[o]? "))
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
sd.wait(60)
sound_name = f"{male_members[f'{male}']}.wav"
wv.write(sound_name, recording, freq, sampwidth=2)
os.path.join(path, sound_name)
elif user.lower() == 'f':
path = r"C:\Users\core i5\Desktop\GitHub\DataSci\Data Analysis and Tools\Dataset\female_voices"
female = str(input("Are you recording your daughter[d], sister[s], aunt[a], mother[m], niece[n], female cousin[fc], or other[o]? "))
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
sd.wait(60)
sound_name = f"{female_members[f'{female}']}.wav"
wv.write(sound_name, recording, freq, sampwidth=2)
os.path.join(path, sound_name)
elif user.lower() == 'e':
print("exiting program....")
break
else:
print("Unrecognized command. Try again\n")
continue
Any help would be appreciated
As Justin said you aren't assigning the return value of os.path.join anywhere. This will create a path, but if you aren't doing anything with it, nothing happens.
You have to use the .write() function to write the file to the os.path.join return value.
This code should work.
# import required libraries
import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
import os
male_members ={'s':'son', 'b':'brother', 'u':'uncle', 'f':'father', 'n':'nephew', 'mc':'male cousin', 'o':'other'}
female_members ={'d':'daughter', 's':'sister', 'a':'aunt', 'm':'mother', 'n':'niece', 'fc':'female cousin', 'o':'other'}
# Sampling frequency
freq = 44100
# Recording duration
duration = 60
while True:
user = str(input("Do you want to record a female [f] or male [m] voice or exit[e]? "))
if user.lower() == 'm':
path = r"C:\Users\core i5\Desktop\GitHub\DataSci\Data Analysis and Tools\Dataset\male_voices"
male = str(input("Are you recording your son[s], brother[b], uncle[u], father[f], nephew[n], male cousin[mc], or other[o]? "))
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
sd.wait(60)
sound_name = f"{male_members[f'{male}']}.wav"
wv.write(os.path.join(path, sound_name), recording, freq, sampwidth=2)
elif user.lower() == 'f':
path = r"C:\Users\core i5\Desktop\GitHub\DataSci\Data Analysis and Tools\Dataset\female_voices"
female = str(input("Are you recording your daughter[d], sister[s], aunt[a], mother[m], niece[n], female cousin[fc], or other[o]? "))
recording = sd.rec(int(duration * freq), samplerate=freq, channels=2)
sd.wait(60)
sound_name = f"{female_members[f'{female}']}.wav"
wv.write(os.path.join(path, sound_name), recording, freq, sampwidth=2)
elif user.lower() == 'e':
print("exiting program....")
break
else:
print("Unrecognized command. Try again\n")
continue
os.path.join(path, sound_name) would return
"C:\Users\core i5\Desktop\GitHub\DataSci\Data Analysis and Tools\Dataset\male_voices\son.wav" (for example). So by writing this code, all you're doing is building a string essentially and returning it no where.
One more trick you can try
Import os
curr_dir = os.getcwd()
os.chdir(path)
# perform the write operation with path as filename
os.chdir(curr_dir)
This is a bit longer than other methods
But this is also a way you can try
My program works fine but when it finished gives error like that :
could not convert to integer . Path ' exitCode'. value too big or too small for Int32
Python 3.7
from re import compile
from os import path, walk
from pywinauto import win32api
from easygui import fileopenbox
from pyautogui import confirm, alert
from sys import exit
def Find_Client_Path():
file_name = compile("LeagueClient.exe")
for driver in win32api.GetLogicalDriveStrings().split("\000")[:-1]:
for root, folders, files in walk(driver):
for file in files:
find_file = file_name.search(file)
if find_file:
return path.join(root, file)
return Find_Path_Manually()
def Find_Path_Manually():
alert(
"Please select LeagueClient.exe in Riot Games / League of Legends /.",
title="Warning",
button="Okay",
)
path = fileopenbox()
if path.find("LeagueClient.exe") != -1:
return path
else:
secim = confirm(
"You choose the worng file. Please select LeagueClient.exe in Riot Games / League of Legends / . If you want to close bot click EXIT button.",
title="UYARI!",
buttons=("OKAY", "EXIT"),
)
if secim == "EXIT":
sys.exit()
elif secim == "OKAY":
return Find_Path_Manually()
This is my main code:
import turtle
import random
from sys import exit
import canvasvg
import os
import tempfile
import shutil
import cairosvg
red = 125
green = 70
blue = 38
pen = 15
def runChk():
runAgain = input("Would you like to return to menu? Y/N (N will exit) \n")
if runAgain.upper() == "Y":
print("Running...")
turtle.clearscreen()
start()
elif runAgain.upper() == "N":
print("Exiting...")
exit()
else:
print("Invalid response.")
runChk()
def saveImg():
print("Done.")
save = input("Would you like to save this tree? Y/N \n")
if save.upper() == "Y":
filename = input("What would you like to name it? \n")
print("Ignore following warning...")
if not filename.lower().endswith('.png'):
filename += '.png'
target_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Images', filename)
tmpdir = tempfile.mkdtemp() # create a temporary directory
tmpfile = os.path.join(tmpdir, 'tmp.svg') # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(target_path, 'wb') as png_output:
cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir) # clean up temp file(s)
print("Saved!")
runChk()
elif save.upper() == "N":
runChk()
else:
print("Invalid response. \n")
saveImg()
def tree(branchLen, red, green, blue, pen):
if branchLen > 3:
pen = pen*0.8
turtle.pensize(pen)
if (red > 10 and green < 140):
red = red - 15
green = green + 8
if branchLen > 5:
angle = random.randrange(18, 55)
angleTwo = 0.5*angle
sub = (0.8*(random.randrange(1,20)))
print("Angle 1: ", angle, "Angle 2: ", angleTwo, " Branch length subtracted by ", sub)
turtle.color(red, green, blue)
turtle.forward(branchLen)
turtle.right(angleTwo)
tree(branchLen-sub, red, green, blue, pen)
turtle.left(angle)
tree(branchLen-sub, red, green, blue, pen)
turtle.right(angleTwo)
turtle.backward(branchLen)
def main():
turtle.colormode(255)
turtle.bgcolor(102, 255, 255)
turtle.left(90)
turtle.up()
turtle.speed(0)
turtle.hideturtle()
turtle.backward(440)
turtle.down()
print("Please wait while I draw...")
tree(random.randrange(80, 95),red,green,blue, pen)
turtle.update()
saveImg()
def start():
live = 1
print("What would you like to do?\n")
usr = input("Type 'run' to start a fractal. \nType 'run static' to create a fractal without live drawing (faster). \nOr 'exit' to exit. \n")
if usr.upper() == "RUN":
live = 1
print("Running...")
main()
elif usr.upper() == "RUN STATIC":
live = 0
print("Running...")
turtle.tracer(0)
main()
elif usr.upper() == "EXIT":
print("Exiting...")
exit()
else:
print("Invalid response.")
start()
start()
it is called fractal.py. I copied that and canvasvg to the main python folder. I created a cx_freeze setup as so:
from cx_Freeze import setup, Executable
# NOTE: you can include any other necessary external imports here aswell
includefiles = [] # include any files here that you wish
includes = []
excludes = []
packages = ['turtle', 'random', 'sys', 'canvasvg', 'os', 'tempfile', 'shutil', 'cairosvg']
exe = Executable(
# what to build
script = "fractal.py", # the name of your main python script goes here
initScript = None,
base = None, # if creating a GUI instead of a console app, type "Win32GUI"
targetName = "Fractal Tree.exe", # this is the name of the executable file
copyDependentFiles = True,
compress = True,
appendScriptToExe = True,
appendScriptToLibrary = True,
icon = None # if you want to use an icon file, specify the file name here
)
setup(
# the actual setup & the definition of other misc. info
name = "Fractal Tree", # program name
version = "0.4.2",
description = 'Creates a fractal tree',
author = "TomSoft Programs",
options = {"build_exe": {"excludes":excludes,"packages":packages,
"include_files":includefiles}},
executables = [exe]
)
When I run cmd as python setup.py build, I get no errors. I go to the build folder and find my fractal.exe program. It closes very quickly and I can't get the full error (because of the speedy closing) but I know it says something like:
ReferenceError: 'module' object has no attribute '_fix_up_module'
What can I do to fix this? I'm very new to python and cx_freeze, so I'm sure I'm doing something wrong in setup.py.
For anyone who finds this, it's a bug with cx_freeze. You've done nothing wrong. Download cx_freeze from here, the bug is fixed at this download location.