I want to read a different windows tab in my computer but it seems to not accept the coordinates that i'm putting, hte coordinates i got were using pyautogui. I'm using jupyter to code it, i'm new to python so most of this code i've found in geeksforgeeks so there is somethings i still dont understand how it works, one of them is why the 'def imToString():".
import numpy as nm
import pytesseract
import cv2
import time
from PIL import ImageGrab
x = 2
time.sleep(5)
def imToString():
pytesseract.pytesseract.tesseract_cmd= r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Tesseract-OCR'
while (True):
cap = ImageGrab.grab(bbox=(220, 370, 335, 330), include_layered_windows=True)
tesstr = pytesseract.image_to_string(
cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
lang ='eng')
print(tesstr)
imToString()
---------------------------------------------------------------------------
SystemError Traceback (most recent call last)
Input In [21], in <cell line: 21>()
17 tesstr = pytesseract.image_to_string(
18 cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
19 lang ='eng')
20 print(tesstr)
---> 21 imToString()
Input In [21], in imToString()
15 while (True):
16 cap = ImageGrab.grab(bbox=(220, 370, 335, 330), include_layered_windows=True)
17 tesstr = pytesseract.image_to_string(
---> 18 cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
19 lang ='eng')
20 print(tesstr)
File C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py:675, in Image.__array__(self, dtype)
673 new["data"] = self.tobytes("raw", "L")
674 else:
--> 675 new["data"] = self.tobytes()
677 return np.array(self._ArrayData(new), dtype)
File C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py:722, in Image.tobytes(self, encoder_name, *args)
720 # unpack data
721 e = _getencoder(self.mode, encoder_name, args)
--> 722 e.setimage(self.im)
724 bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
726 data = []
SystemError: tile cannot extend outside image
Related
so I am trying to pick a folder, select every photo, watermark it with an individual text and safe it in a different folder.
I have watched a lot of YouTube Videos and googled a lot but I can't help it anymore... Im always getting error messages and I can't see why.
So my current code is:
import PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os
for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
draw = ImageDraw.Draw(f)
text = "Test, 22.01.2021"
font = ImageFont.truetype("arial.ttf",75)
textwidth, textheight = draw.textsize(text, font)
width, height = f.size
x=width/2-textwidth/2
y=height-textheight-300
draw.text((x,y), text, font=font)
fn, fext = os.path.splitext(f)
i.save('Test/{}.jpg'.format(fn))
Errors:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in Draw(im, mode)
464 try:
--> 465 return im.getdraw(mode)
466 except AttributeError:
AttributeError: 'str' object has no attribute 'getdraw'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-5-5c49936ed159> in <module>
9 if f.endswith('.jpg'):
10 i = Image.open(f)
---> 11 draw = ImageDraw.Draw(f)
12 text = "Jonas Knaab, 22.01.2021"
13 font = ImageFont.truetype("arial.ttf",75)
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in Draw(im, mode)
465 return im.getdraw(mode)
466 except AttributeError:
--> 467 return ImageDraw(im, mode)
468
469
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in __init__(self, im, mode)
57 defaults to the mode of the image.
58 """
---> 59 im.load()
60 if im.readonly:
61 im._copy() # make it writeable
AttributeError: 'str' object has no attribute 'load'
------------------
Maybe you guys can help me somehow?
Cheers
!!EDIT!!
after changing ..."Draw(f)" to "Draw(i) I do not get the same error messages but it still doesn't work.
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-9-3b2bbb3d5783> in <module>
11 draw = ImageDraw.Draw(i)
12 text = "Jonas Knaab, 22.01.2021"
---> 13 font = ImageFont.truetype("arial.ttf",75)
14 textwidth, textheight = draw.textsize(text, font)
15 width, height = f.size
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in truetype(font, size, index, encoding, layout_engine)
640
641 try:
--> 642 return freetype(font)
643 except OSError:
644 if not isPath(font):
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in freetype(font)
637
638 def freetype(font):
--> 639 return FreeTypeFont(font, size, index, encoding, layout_engine)
640
641 try:
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in __init__(self, font, size, index, encoding, layout_engine)
186 return
187 self.font = core.getfont(
--> 188 font, size, index, encoding, layout_engine=layout_engine
189 )
190 else:
OSError: cannot open resource
You're using string as an argument to ImageDraw.Draw(). Use i variable instead of f.
i = Image.open(f)
draw = ImageDraw.Draw(i)
Both of these code throw an error. I am not sure what is the exact cause? I am running using Jupyter notebook.
from __future__ import print_function, division
import os
import torch
import torch.nn as nn
import torchvision
from torch.autograd import Variable
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
def show_landmarks(image, landmarks):
"""Show image with landmarks"""
plt.imshow(image)
plt.scatter(landmarks[:, 0], landmarks[:, 1], s=80, marker='.', c='b')
plt.pause(0.001) # pause a bit so that plots are updated
plt.figure()
img_name = "faces/person-7.jpg"
print(img_name)
img = io.imread(img_name)
print('here')
show_landmarks(img, landmarks)
plt.show()
###def show_landmarks(image, landmarks):
### """Show image with landmarks"""
### plt.imshow(image)
### plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r')
### plt.pause(0.001) # pause a bit so that plots are updated
###plt.figure()
###show_landmarks(io.imread(os.path.join('data/faces/', img_name)),
### landmarks)
###plt.show()
The error is:
faces/person-7.jpg
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-972bef8edc6f> in <module>
9 print(img_name)
10
---> 11 img = io.imread(img_name)
12 print('here')
13 show_landmarks(img, landmarks)
~/anaconda3/lib/python3.7/site-packages/skimage/io/_io.py in imread(fname, as_gray, plugin, **plugin_args)
46
47 with file_or_url_context(fname) as fname:
---> 48 img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
49
50 if not hasattr(img, 'ndim'):
~/anaconda3/lib/python3.7/site-packages/skimage/io/manage_plugins.py in call_plugin(kind, *args, **kwargs)
207 (plugin, kind))
208
--> 209 return func(*args, **kwargs)
210
211
~/anaconda3/lib/python3.7/site-packages/skimage/io/_plugins/imageio_plugin.py in imread(*args, **kwargs)
8 #wraps(imageio_imread)
9 def imread(*args, **kwargs):
---> 10 return np.asarray(imageio_imread(*args, **kwargs))
~/anaconda3/lib/python3.7/site-packages/imageio/core/functions.py in imread(uri, format, **kwargs)
263
264 # Get reader and read first
--> 265 reader = read(uri, format, "i", **kwargs)
266 with reader:
267 return reader.get_data(0)
~/anaconda3/lib/python3.7/site-packages/imageio/core/functions.py in get_reader(uri, format, mode, **kwargs)
180 modename = MODENAMES.get(mode, mode)
181 raise ValueError(
--> 182 "Could not find a format to read the specified file in %s mode" % modename
183 )
184
ValueError: Could not find a format to read the specified file in single-image mode
<Figure size 432x288 with 0 Axes>
The error seems to be related to line 11 - img = io.imread(img_name). This error is likely being thrown, because you aren't using the optional pluginstr with imread or because imread cannot find a suitable plugin to read the image file.
skimage.io.imread with parameters:
skimage.io.imread(fname, as_gray=False, plugin=None, **plugin_args)
pluginstr, optional
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.
You can troubleshoot the error, by trying various plugins like the example below shows:
io.imread(f.name, plugin="tifffile")
Here is a list of available plugins
I try to make Persian Wordcloud in python. I run package but get error. I try regex and delete some unicode from text but does not work. text is persian twit and I crawl them from twitter.
This is my code:
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
from persian_wordcloud.wordcloud import PersianWordCloud, add_stop_words
from wordcloud import STOPWORDS as EN_STOPWORDS3
stopwords = EN_STOPWORDS
wordcloud = PersianWordCloud(
only_persian=True,
max_words=100,
stopwords=stopwords,
margin=0,
width=800,
height=800,
min_font_size=1,
max_font_size=500,
background_color="white"
).generate(All_Khashm_str)
plt.figure(figsize=(15,15))
image = wordcloud.to_image()
imgplot = plt.imshow(image)
plt.show()
and get this error:
AssertionError Traceback (most recent call last)
<ipython-input-40-f8bfa84af8e1> in <module>
11 max_font_size=500,
12 background_color="white"
---> 13 ).generate(All_Khashm_str)
14
15
~/.local/lib/python3.6/site-packages/persian_wordcloud/wordcloud.py in generate(self, text)
142 """
143 # reshape persian words
--> 144 text = get_display(arabic_reshaper.reshape(text))
145 return self.generate_from_text(text)
146
~/.local/lib/python3.6/site-packages/bidi/algorithm.py in get_display(unicode_or_str, encoding, upper_is_rtl, base_dir, debug)
646 resolve_weak_types(storage, debug)
647 resolve_neutral_types(storage, debug)
--> 648 resolve_implicit_levels(storage, debug)
649 reorder_resolved_levels(storage, debug)
650 apply_mirroring(storage, debug)
~/.local/lib/python3.6/site-packages/bidi/algorithm.py in resolve_implicit_levels(storage, debug)
464 # only those types are allowed at this stage
465 assert _ch['type'] in ('L', 'R', 'EN', 'AN'),\
--> 466 '%s not allowed here' % _ch['type']
467
468 if _embedding_direction(_ch['level']) == 'L':
AssertionError: not allowed here
Thank you for help. Is this a bug?
I have 64 bit windows 10 OS
I have installed python 3.6.8
I have installed torch and torchtext using pip.
torch version is 1.2.0
I am trying to load AG_NEWS dataset using below code:
import torch
import torchtext
from torchtext.datasets import text_classification
NGRAMS = 2
import os
if not os.path.isdir('./.data'):
os.mkdir('./.data')
train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](root='./.data', ngrams=NGRAMS, vocab=None)
On the last statement of above code, I am getting below error:
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-1-7e8544fdaaf6> in <module>
6 if not os.path.isdir('./.data'):
7 os.mkdir('./.data')
----> 8 train_dataset, test_dataset = text_classification.DATASETS['AG_NEWS'](root='./.data', ngrams=NGRAMS, vocab=None)
9 # BATCH_SIZE = 16
10 # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
c:\users\pramodp\appdata\local\programs\python\python36\lib\site-packages\torchtext\datasets\text_classification.py in AG_NEWS(*args, **kwargs)
168 """
169
--> 170 return _setup_datasets(*(("AG_NEWS",) + args), **kwargs)
171
172
c:\users\pramodp\appdata\local\programs\python\python36\lib\site-packages\torchtext\datasets\text_classification.py in _setup_datasets(dataset_name, root, ngrams, vocab, include_unk)
126 if vocab is None:
127 logging.info('Building Vocab based on {}'.format(train_csv_path))
--> 128 vocab = build_vocab_from_iterator(_csv_iterator(train_csv_path, ngrams))
129 else:
130 if not isinstance(vocab, Vocab):
c:\users\pramodp\appdata\local\programs\python\python36\lib\site-packages\torchtext\vocab.py in build_vocab_from_iterator(iterator)
555 counter = Counter()
556 with tqdm(unit_scale=0, unit='lines') as t:
--> 557 for tokens in iterator:
558 counter.update(tokens)
559 t.update(1)
c:\users\pramodp\appdata\local\programs\python\python36\lib\site-packages\torchtext\datasets\text_classification.py in _csv_iterator(data_path, ngrams, yield_cls)
33 with io.open(data_path, encoding="utf8") as f:
34 reader = unicode_csv_reader(f)
---> 35 for row in reader:
36 tokens = ' '.join(row[1:])
37 tokens = tokenizer(tokens)
c:\users\pramodp\appdata\local\programs\python\python36\lib\site-packages\torchtext\utils.py in unicode_csv_reader(unicode_csv_data, **kwargs)
128 maxInt = int(maxInt / 10)
129
--> 130 csv.field_size_limit(sys.maxsize)
131
132 if six.PY2:
OverflowError: Python int too large to convert to C long
I think the issue is with either windows os or torchtext because I am getting same error for below code as well.
pos = data.TabularDataset( path='data/pos/pos_wsj_train.tsv', format='tsv', fields=[('text', data.Field()),
('labels', data.Field())])
Can somebody please help? and mainly I don't have any large numerical values in the file.
I also encountered a similar problem. I changed a line of code in my torchtext\utils.py file and my error disappeared.
Changed this:
csv.field_size_limit(sys.maxsize)
To this:
csv.field_size_limit(maxInt)
I have been processing still images without error.
When I attempt to run the below code for the video processing, I am receiving the error:
OS Error: cannot identify image file 'solidWhiteRight.mp4'
and then I cannot proceed.
Anyone able to figure out what is causing the error?
THE COMPLETE ERROR CODE:
OSError: cannot identify image file 'solidWhiteRight.mp4'
OSError Traceback (most recent call last)
<ipython-input-85-8871a0549a09> in <module>()
1 white_output = 'white.mp4'
2 clip1 = VideoFileClip('solidWhiteRight.mp4')
----> 3 white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
4 get_ipython().magic('time white_clip.write_videofile(white_output, audio=False)')
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/video/VideoClip.py in fl_image(self, image_func, apply_to)
512 `get_frame(t)` by another frame, `image_func(get_frame(t))`
513 """
--> 514 return self.fl(lambda gf, t: image_func(gf(t)), apply_to)
515
516 # --------------------------------------------------------------
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/Clip.py in fl(self, fun, apply_to, keep_duration)
134
135 #mf = copy(self.make_frame)
--> 136 newclip = self.set_make_frame(lambda t: fun(self.get_frame, t))
137
138 if not keep_duration:
<decorator-gen-178> in set_make_frame(self, mf)
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/decorators.py in outplace(f, clip, *a, **k)
12 """ Applies f(clip.copy(), *a, **k) and returns clip.copy()"""
13 newclip = clip.copy()
---> 14 f(newclip, *a, **k)
15 return newclip
16
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/video/VideoClip.py in set_make_frame(self, mf)
652 """
653 self.make_frame = mf
--> 654 self.size = self.get_frame(0).shape[:2][::-1]
655
656
<decorator-gen-135> in get_frame(self, t)
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/decorators.py in wrapper(f, *a, **kw)
87 new_kw = {k: fun(v) if k in varnames else v
88 for (k,v) in kw.items()}
---> 89 return f(*new_a, **new_kw)
90 return decorator.decorator(wrapper)
91
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/Clip.py in get_frame(self, t)
93 return frame
94 else:
---> 95 return self.make_frame(t)
96
97 def fl(self, fun, apply_to=[] , keep_duration=True):
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/Clip.py in <lambda>(t)
134
135 #mf = copy(self.make_frame)
--> 136 newclip = self.set_make_frame(lambda t: fun(self.get_frame, t))
137
138 if not keep_duration:
/home/michael/anaconda3/lib/python3.5/site-packages/moviepy/video/VideoClip.py in <lambda>(gf, t)
512 `get_frame(t)` by another frame, `image_func(get_frame(t))`
513 """
--> 514 return self.fl(lambda gf, t: image_func(gf(t)), apply_to)
515
516 # --------------------------------------------------------------
<ipython-input-84-5748bb68776c> in process_image(image)
6 #Read in image
7 #Grayscale the image
----> 8 image = mpimg.imread('solidWhiteRight.mp4')
9 gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
10
/home/michael/anaconda3/lib/python3.5/site-packages/matplotlib/image.py in imread(fname, format)
1304
1305 if ext not in handlers:
-> 1306 im = pilread(fname)
1307 if im is None:
1308 raise ValueError('Only know how to handle extensions: %s; '
/home/michael/anaconda3/lib/python3.5/site-packages/matplotlib/image.py in pilread(fname)
1282 except ImportError:
1283 return None
-> 1284 image = Image.open(fname)
1285 return pil_to_array(image)
1286
/home/michael/anaconda3/lib/python3.5/site-packages/PIL/Image.py in open(fp, mode)
2315
2316 raise IOError("cannot identify image file %r"
-> 2317 % (filename if filename else fp))
2318
2319 #
OSError: cannot identify image file 'solidWhiteRight.mp4'
THE CODE FOR VIDEO PROCESSING:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
import os
os.listdir()
from moviepy.editor import VideoFileClip
def process_image(image):
# The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the final output (image with lines are drawn on lanes)
#Read in image
#Grayscale the image
image = mpimg.imread(solidWhiteRight.mp4)
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
#Define a kernel size and apply Gaussian smoothing (blurring)
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size,kernel_size),0)
#Define the parameters for the Canny edge detection algorithm and apply
low_threshold = 50
high_threshold = 250
edges = cv2.Canny(blur_gray, low_threshold, high_threshold)
#Create a "masked edges" image using cv2.fillPoly()
mask = np.zeros_like(edges)
ignore_mask_color = 255
#Define a four-side polygon to mask the image
imshape = image.shape
vertices = np.array([[(0, imshape[0]),(450,290),(490, 290),(imshape[1],imshape[0])]], dtype=np.int32)
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges,mask)
#Define the Hough transform parameters
#Make a blank the same size as our image to draw on
rho = 2 #Distance resolution in pixels of the Hough grid
theta = np.pi/180 #Angular resolution in radians of the Hough grid
threshold = 15 #Minimum number of votes (intersections in Hough grid cell)
min_line_length = 40 #Minimum number of pixels making up a line
max_line_gap = 20 #Maximum gap in pixels between connectable line segments
line_image = np.copy(image)*0 #Creating a blank to draw lines on
#Run Hough on edge detected image
#Output "lines" is an array containing endpoints of detected line segments
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),
min_line_length, max_line_gap)
#Iterate over the output "lines' and draw lines on a blank image
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)
#Create a "color" binary image to combine with the line image
color_edges = np.dstack((edges, edges, edges))
#Draw the lines on the edge image
lines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)
return line_edges
#Solid white first
white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False)
#Play video inline
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output))
ERROR: OS Error: cannot identify image file 'solidWhiteRight.mp4'
The answer is that:
Line 8:
image = mpimg.imread(solidWhiteRight.mp4)
Is trying to process a still image file. If you comment it out,
the code runs properly.