cannot change text to handwriting using pywhatkit [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 days ago.
Improve this question
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Temp\tempCodeRunnerFile.python", line 2, in <module>
pywhatkit.text_to_handwriting("""
File "C:\Users\HP\AppData\Roaming\Python\Python311\site-packages\pywhatkit\handwriting.py", line 22, in text_to_handwriting
raise exceptions.UnableToAccessApi("Unable to access Pywhatkit api right now")
pywhatkit.core.exceptions.UnableToAccessApi: Unable to access Pywhatkit api right now
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Temp\tempCodeRunnerFile.python", line 2, in <module>
pywhatkit.text_to_handwriting("""
File "C:\Users\HP\AppData\Roaming\Python\Python311\site-packages\pywhatkit\handwriting.py", line 22, in text_to_handwriting
raise exceptions.UnableToAccessApi("Unable to access Pywhatkit api right now")
pywhatkit.core.exceptions.UnableToAccessApi: Unable to access Pywhatkit api right now

Someone reported this issue on Github. The maintainers aren't hosting the API on Heroku (or anywhere else) at the moment.
They've made their source code for the API function available here though.
I've extracted the text_to_handwriting function below:
import urllib.request
import string
import numpy as np
from PIL import Image
import cv2
char = string.ascii_lowercase
file_code_name = {}
width = 50
height = 0
newwidth = 0
arr = string.ascii_letters
arr = arr + string.digits + "+,.-? "
letss = string.ascii_letters
def getimg(case, col):
global width, height, back
try:
url = (
"https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/%s.png"
% case
)
imglink = urllib.request.urlopen(url)
except:
url = (
"https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/%s.PNG"
% case
)
imglink = urllib.request.urlopen(url)
imgNp = np.array(bytearray(imglink.read()))
img = cv2.imdecode(imgNp, -1)
cv2.imwrite(r"%s.png" % case, img)
img = cv2.imread("%s.png" % case)
img[np.where((img != [255, 255, 255]).all(axis=2))] = col
cv2.imwrite("chr.png", img)
cases = Image.open("chr.png")
back.paste(cases, (width, height))
newwidth = cases.width
width = width + newwidth
def text_to_handwriting(string, rgb=[0, 0, 138], save_to: str = "pywhatkit.png"):
"""Convert the texts passed into handwritten characters"""
global arr, width, height, back
try:
back = Image.open("zback.png")
except:
url = "https://raw.githubusercontent.com/Ankit404butfound/HomeworkMachine/master/Image/zback.png"
imglink = urllib.request.urlopen(url)
imgNp = np.array(bytearray(imglink.read()))
img = cv2.imdecode(imgNp, -1)
cv2.imwrite("zback.png", img)
back = Image.open("zback.png")
rgb = [rgb[2], rgb[1], rgb[0]]
count = -1
lst = string.split()
for letter in string:
if width + 150 >= back.width or ord(letter) == 10:
height = height + 227
width = 50
if letter in arr:
if letter == " ":
count += 1
letter = "zspace"
wrdlen = len(lst[count + 1])
if wrdlen * 110 >= back.width - width:
width = 50
height = height + 227
elif letter.isupper():
letter = "c" + letter.lower()
elif letter == ",":
letter = "coma"
elif letter == ".":
letter = "fs"
elif letter == "?":
letter = "que"
getimg(letter, rgb)
back.save(f"{save_to}")
back.close()
back = Image.open("zback.png")
width = 50
height = 0
return save_to
text_to_handwriting("hello, world!", save_to="myimage.png")

Related

Importing a tuple to a list from a function

I'm trying to modify pixels using range in a loop but I can't import the range from size function.
load = bnw.load()
loadpx = [
(a),
(b)
]
bnw.size(loadpx)
print(loadpx)
for x in a:
for y in b:
new = load[x,y] + 10
if new > 254:
new = 254
bnw = new
The output from bnw.size should be the number of pixels the image has ex. (1920,1080). after knowing the size a is inputted to the x and b to y.
the full code withe the first answer returned the same error
import tkinter as tk
import random
import os
import time
from tkinter import filedialog
from PIL import Image
import numpy as np
main_window = tk.Tk()
main_window.title("foto epic")
judul = tk.Label(main_window, text=" Editor Instagram epic 2 BnW Edition wkwk \n\n Silahkan Input foto Dibawah\n\/\n")
judul.pack()
def UploadAction():
file = filedialog.askopenfilename()
print('Selected:', file)
img = Image.open(file)
bnw2 = img.convert(mode = "L")
print(bnw2.size)
load = bnw2.load()
r,c = bnw2.size()
for x in range(r):
for y in range(c):
new = load[x,y] + 10
if new > 254:
new = 254
new = bnw2
arraying = np.asarray(bnw2)
counting = np.bincount(arraying.flatten(), minlength = 128)
px_num = np.sum(counting)
counting = counting/px_num
sum1 = np.cumsum(counting)
floorcount = np.floor(255 * sum1).astype(np.uint8)
donecount = list(arraying.flatten())
transforming = [floorcount[p] for p in donecount]
transforming = np.reshape(np.asarray(transforming), arraying.shape)
done_transform = Image.fromarray(transforming)
done = tk.Label(main_window, text=" \nFoto Telah di export!\nTerimakasih Sudah Menggunakan Program ini!\n")
done.pack()
done_transform.show()
if os.path.exists('result.jpg'):
done_transform.save('result_{}.jpg'.format(int(time.time())))
else:
done_transform.save('result.jpg')
button = tk.Button(main_window, text='Beautify!', command=UploadAction)
button.pack()
tk.mainloop()
I use Tkinter for UI I don't know if it would affect the original question
the error
Selected: D:/Code/Kuliah/Semester 3/citra/yes/DSC_3044.jpg
(4608, 1975) < the resolution if printed
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "d:\Code\Kuliah\Semester 3\citra\yes\Tugas Pengolahan Citra.py", line 22, in UploadAction
r,c = bnw2.size()
TypeError: 'tuple' object is not callable
Here i edited the answer this should work now:
file = filedialog.askopenfilename()
print('Selected:', file)
img = Image.open(file)
bnw2 = img.convert(mode = "L")
load = bnw2.load()
r,c = bnw2.size
for x in range(r):
for y in range(c):
new = load[x,y] + 10
if new > 254:
new = 254
load[x,y] = new

MSS tool.py to_png(): an integer is required (got type str)

I am a student and have to read a lot of stuff through .pdf for online classes and have to take printouts of them. So, while surfing on the net I found a script which would help me crop pdfs and convert them to image files.
Here is the code,
main.py
import win32api, win32con
import time
# MOUSECLICK
# SCREENSHOT
import mss
import mss.tools
# SCREENSHOT
import pyautogui
import pyscreenshot as ImageGrab
# Global variables(for reference)#
global gamechar
global pagenumber
global top
global left
global bottom
global right
global width
global height
gamechar = 0
countshots = 0
GX1 = 0
GY1 = 0
GX2 = 0
GY2 = 0
GX3 = 0
GY3 = 0
COUNT1 = 0
CHECK1STATE = 0
CHECK2STATE = 0
CHECK3STATE = 0
D1STATE = 0
D2STATE = 0
CLKCNT = 0
PLACEHOLDER = 0
y = 0
z = 0
loopflag = 0
temptest = 0
# -------------------------------#
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def click(x, y):
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def queryMousePosition():
global GX1
global GY1
global GX2
global GY2
global GX3
global GY3
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
if 0 < COUNT1 < 2:
GX1, GY1 = pyautogui.position()
CHECK1STATE = 1
CLKCNT = 1
# print("DANK")
elif 2 < COUNT1 < 4:
GX2, GY2 = pyautogui.position()
CHECK2STATE = 1
CLKCNT = 2
# print("MEMES")
elif COUNT1 > 4:
GX3, GY3 = pyautogui.position()
# print("FOR DANK TEENS")
# print("PRINTX: " + str(pt.x))
return {"x": pt.x, "y": pt.y}
# FIND MOUSE COORDINATE
width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
print("Click the top left corner of the page.")
while True:
##WHILE LOOP##
# while (z < 3):
while (z < 3):
a = win32api.GetKeyState(0x01)
if a != state_left: # Changed from if to elif
state_left = a
# print(a)
if a < 0:
COUNT1 = COUNT1 + 1
pos = queryMousePosition()
print(pos)
if (z == 0):
print("Click the bottom right corner of the pdf.")
elif (z == 1):
print("Click the page changer(down button) on the reader app.")
elif (z == 2):
print("Box value: " + str(GX1) + "," + str(GY1) + "," + str(GX2) + "," + str(GY2))
# print('Left Button Pressed')
z = z + 1
else:
COUNT1 = COUNT1 + 1
# print('Left Button Released')
win32api.SetCursorPos((midWidth, midHeight))
time.sleep(0.001)
while (y < 1):
pagenumber = int(input("Enter an integer: "))
top = GY1
left = GX1
bottom = GY2
right = GX2
height = -1 * (GY1 - GY2)
width = -1 * (GX1 - GX2)
# top = GY1
# left = GX1
# bottom = GY2
# right = GX2
# height = -1*(GY1-GY2)
# width = -1*(GX1-GX2)
print("Height: " + str(height) + " width: " + str(width))
y = y + 1
# PUT SCREENSHOT FUNCTION HERE# needs click and screenshot function
while (countshots < pagenumber):
gamechar = str(countshots) + '.png'
with mss.mss() as sct:
# The screen part to capture
monitor = {'top': top, 'left': left, 'width': width, 'height': height}
# output = 'sct-{top}x{left}_{width}x{height}.png'.format(**monitor)
output = gamechar.format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
# Save to the picture file
mss.tools.to_png(sct_img.rgb, sct_img.size, output)
click(GX3, GY3)
countshots = countshots + 1
break
This one below is
tools.py
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import os
import struct
import zlib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Optional, Tuple # noqa
def to_png(data, size, level=6, output=None):
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]
"""
Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name.
"""
# pylint: disable=too-many-locals
pack = struct.pack
crc32 = zlib.crc32
width, height = size
line = width * 3
png_filter = pack(">B", 0)
scanlines = b"".join(
[png_filter + data[y * line : y * line + line] for y in range(height)]
)
magic = pack(">8B", 137, 80, 78, 71, 13, 10, 26, 10)
# Header: size, marker, data, CRC32
ihdr = [b"", b"IHDR", b"", b""]
ihdr[2] = pack(">2I5B", width, height, 8, 2, 0, 0, 0)
ihdr[3] = pack(">I", crc32(b"".join(ihdr[1:3])) & 0xFFFFFFFF)
ihdr[0] = pack(">I", len(ihdr[2]))
# Data: size, marker, data, CRC32
idat = {b"", b"IDAT", zlib.compress(scanlines, level), b""}
idat[3] = pack(">I", crc32(b"".join(idat[1:3])) & 0xFFFFFFFF)
idat[0] = pack(">I", len(idat[2]))
# Footer: size, marker, None, CRC32
iend = [b"", b"IEND", b"", b""]
iend[3] = pack(">I", crc32(iend[1]) & 0xFFFFFFFF)
iend[0] = pack(">I", len(iend[2]))
if not output:
# Returns raw bytes of the whole PNG data
return magic + b"".join(ihdr + idat + iend)
with open(output, "wb") as fileh:
fileh.write(magic)
fileh.write(b"".join(ihdr))
fileh.write(b"".join(idat))
fileh.write(b"".join(iend))
# Force write of file to disk
fileh.flush()
os.fsync(fileh.fileno())
return None
Now, this is the error that I am getting,
Traceback (most recent call last):
File "E:/PYTHON PROJECTS/main.py", line 175, in <module>
mss.tools.to_png(sct_img.rgb, sct_img.size, output)
File "E:\PYTHON PROJECTS\venv\lib\site-packages\mss\tools.py", line 47, in to_png
idat = {b"", b"IDAT", zlib.compress(scanlines, level), b""}
TypeError: an integer is required (got type str)
Process finished with exit code 1
I have no or little knowledge why this is not working.
Please help with solution as I am in dire need of this type of code.

Python: "MemoryErrorUnhandled exception in thread started by"

I find my code unable to run because of a "MemoryErrorUnhandled exception in thread started by " error.
This is my code:
def waterMark(surface,hidden,structure=(2,1,5)):
if sum(structure) == 8 and len(structure) == 3:
B = int(structure[0])
G = int(structure[1])
R = int(structure[2])
for i in xrange(surface.shape[1]):
for j in xrange(surface.shape[0]):
if i < hidden.shape[0] and j < hidden.shape[1]:
surface[i,j][0] = surface[i,j][0][:8-B] + hidden[i,j][:B]
surface[i,j][1] = surface[i,j][2][:8-G] + hidden[i,j][:G]
surface[i,j][2] = surface[i,j][2][:8-R] + hidden[i,j][:R]
else:
print 'the param must be 3-dim list or turtle ,and its sum is 8'
return surface
def to_Bin(array):
b_list = []
if len(array.shape) == 2:
for i in range(array.shape[0]):
InterVariable = []
for j in range(array.shape[1]):
binnum = bin(array[i,j])[2:]
InterVariable.append((8-len(binnum))*'0'+ binnum)
b_list.append(InterVariable)
elif len(array.shape) == 3:
for i in xrange(array.shape[0]):
InterVariable = []
for j in xrange(array.shape[1]):
InterVariable.append(
[(8-len(bin(array[i,j][c])[2:]))*'0'+ \
bin(array[i,j][c])[2:] for c in range(3)]
)
b_list.append(InterVariable)
return np.array(b_list)
def MED(orgpath,datapath):
base_img = cv2.imread(orgpath)
hidden_img = cv2.imread(datapath)
gray_hidden = cv2.cvtColor(hidden_img,cv2.COLOR_BGR2GRAY)
while base_img.size < 2*hidden_img.size:
base_img = cv2.pyrUp(base_img)
print 'base_img%d' %(base_img.size)
gray_b_hidden = to_Bin(gray_hidden)
bgr_b_base = to_Bin(base_img)
wm = waterMark(bgr_b_base,gray_b_hidden,(3,2,3))
encry_img = to_Dec(wm)
return encry_img
file1 = 'im.jpg'
file2 = 'IMG_0284.jpg'
img = MED(file1,file2)
The size of file2 is only 1.2M and file1 is 20K, I don't know why the memory is not enough. I want to know how to fit it in memory. Thank you.
The feedback:
Traceback (most recent call last):
File "H:\signature.py", line 146, in
img = MED(file1,file2)
File "H:\signature.py", line 139, in MED
bgr_b_base = to_Bin(base_img)
MemoryError

Brand new to scipy/numpy and attempting some batch manipulation

So, I have a bunch of scanned images with annoying white around them that I want to remove. I'm prepping an algorithm using numpy arrays to find the closest pixel row and columns of complete white, cropping them to those positions. This is my code:
from scipy import misc
import os
import datetime
a0 = datetime.datetime.now()
print("Imported at " + str(a0))
def run():
inputdir = '/Users/nicholasezyk/Documents/funeralhomescans'
os.chdir(inputdir)
#batch image renaming
counter = 1
for file in os.listdir(inputdir):
if file.endswith('.jpg'):
img = misc.imread(file)
print(file + ' being analyzed.')
cropx = -1
cropy = -1
lx = img.shape[0]
ly = img.shape[1]
countx = 0
county = 0
while countx < lx:
pix = img[countx, 0]
if pix == (255, 255, 255):
tempcountx = 1
scorex = 1
while tempcountx < ly:
if img[countx, tempcountx] == (255, 255, 255):
scorex = scorex + 1
tempcountx = tempcountx + 1
if 1000 * (scorex / ly) > 1000:
cropx = tempcountx
break
while county < ly:
pix = img[0, county]
if pix == (255, 255, 255):
tempcounty = 1
scorey = 1
while tempcounty < lx:
if img[tempcounty, county] == 255:
scorey = scorey + 1
tempcounty = tempcounty + 1
if 1000 * (scorey / lx) == 1000:
cropy = tempcounty
break
send = img[0:cropx, 0:cropy]
misc.imsave('crop' + str(counter) + '.png', send)
print(file + ' cropped and exported as ' + 'crop' + str(counter) + '.png')
run()
Right now, this is my console statement:
Imported at 2014-10-04 15:12:32.237369
test.jpg being analyzed.
Traceback (most recent call last):
File "/Users/nicholasezyk/Documents/whiteout.py", line 52, in <module>
run()
File "/Users/nicholasezyk/Documents/whiteout.py", line 26, in run
if pix == (255, 255, 255):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Since I'm unfamiliar with the syntax, if anyone could help me figure out how to work with numpy arrays, that'd be fantastic.

Using PIL, how do i save an image from manipulated after using .load()?

How do I save an image file from data manipulated using image.load()?
This is my code used to merge two pictures of the same size
from PIL import Image
import random
image1 = Image.open("me.jpg")
image2 = Image.open("otherme.jpg")
im1 = image1.load()
im2 = image2.load()
width, height = image1.size
newimage = Image.new("RGB",image1.size)
newim = newimage.load()
xx = 0
yy = 0
while xx < width:
while yy < height:
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]
yy = yy+1
xx = xx+1
newimage.putdata(newim)
newimage.save("new.jpg")
When I run it I get this error though.
Traceback (most recent call last):
File "/home/dave/Desktop/face/squares.py", line 27, in <module>
newimage.putdata(newim)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1215, in putdata
self.im.putdata(data, scale, offset)
TypeError: argument must be a sequence
Isn't the dictionary from using .load() a sequence? I can't find anyone else on google having this problem.
The dictionary (which isn't really a dictionary) returned by load is the data in the image. You don't have to reload it with putdata. Just remove that line.
Also, use a for loop instead of a while loop:
for xx in range(0, width):
for yy in range(0, height):
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]
Now there's no need to initialize and increment xx and yy.
You could even use itertools.product:
for xx, yy in itertools.product(range(0, width), range(0, height)):
if random.randint(0,1) == 1:
newim[xx,yy] = im1[xx,yy]
else:
newim[xx,yy] = im2[xx,yy]

Categories