I need to resize an screenshot taken by mss in order to get better reading by pytesseract and i get it done with pil+pyscreenshot but can't get it to with mss.
from numpy import array, flip
from mss import mss
from pytesseract import image_to_string
from time import sleep
def screenshot():
cap = array(mss().grab({'top': 171, 'left': 1088, 'width': 40, 'height': 17}))
cap = flip(cap[:, :, :3], 2)
return cap
def read(param):
tesseract = image_to_string(param)
return tesseract
while True:
print(read(screenshot()))
sleep(2)
here its working with pyscreenshot
from time import sleep
from PIL import Image, ImageOps
import pyscreenshot as ImageGrab
import pytesseract
while 1:
test = ImageGrab.grab(bbox=(1088,171,1126,187))
testt = ImageOps.fit(test, (50, 28), method=Image.ANTIALIAS)
testt.save('result.png')
read = pytesseract.image_to_string(testt)
print(read)
sleep(2)
And, i don't care about maintain aspect radio, works better that way with pytesseract.
Related
Hello everyone, im new hier and want to start learning how machine learning works. So i want to build a machine learning email spam detector in colab, but something seems to be wrong:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import nltk import string
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from google.colab import files
uploaded = files.upload() filename = ('spam.tsv')
content = []
with open(filename, "r") as file_content:
for line in file_content.readlines():
line = line.strip() content.append(line)
spam = line
#print(spam) for testinn if it is working
z = spam['EmailText']
y = spam["Label"]
z_train, z_test,y_train, y_test = train_test_split(z,y,test_size = 0.2)
count_vector = CountVectorizer()
features = count_vector.transform(z_train)
model = svm.SVC()
model.fit(features,y_train)
features_test = count_vector.transform(z_test)
print(model.score(features_test,y_test))`
NotFittedError: Vocabulary not fitted or provided TypeError: string indices must be integers
i tried everything but nothing works really haha
i hope, you can help
thank you
I am using tensorRT to perform inference with CUDA. I'd like to use CuPy to preprocess some images that I'll feed to the tensorRT engine. The preprocessing function, called my_function, works fine as long as tensorRT is not run between different calls of the my_function method (see code below). Specifically, the issue is not strictly related by tensorRT but by the fact that tensorRT inference requires to be wrapped by push and pop operations of the pycuda context.
With respect to the following code, the last execution of my_function will raise the following error:
File "/home/ubuntu/myfile.py", line 188, in _pre_process_cuda
img = ndimage.zoom(img, scaling_factor)
File "/home/ubuntu/.local/lib/python3.6/site-packages/cupyx/scipy/ndimage/interpolation.py", line 482, in zoom
kern(input, zoom, output)
File "cupy/core/_kernel.pyx", line 822, in cupy.core._kernel.ElementwiseKernel.__call__
File "cupy/cuda/function.pyx", line 196, in cupy.cuda.function.Function.linear_launch
File "cupy/cuda/function.pyx", line 164, in cupy.cuda.function._launch
File "cupy_backends/cuda/api/driver.pyx", line 299, in cupy_backends.cuda.api.driver.launchKernel
File "cupy_backends/cuda/api/driver.pyx", line 124, in cupy_backends.cuda.api.driver.check_status
cupy_backends.cuda.api.driver.CUDADriverError: CUDA_ERROR_INVALID_HANDLE: invalid resource handle
Note: in the following code I haven't reported the entire tensorRT inference code. In fact, simply pushing and popping a pycuda context generates the error
Code:
import numpy as np
import cv2
import time
from PIL import Image
import requests
from io import BytesIO
from matplotlib import pyplot as plt
import cupy as cp
from cupyx.scipy import ndimage
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
def my_function(numpy_frame):
dtype = 'float32'
img = cp.array(numpy_frame, dtype='float32')
# print(img)
img = ndimage.zoom(img, (0.5, 0.5, 3))
img = (cp.array(2, dtype=dtype) / cp.array(255, dtype=dtype)) * img - cp.array(1, dtype=dtype)
img = img.transpose((2, 0, 1))
img = img.ravel()
return img
# load image
url = "https://www.pexels.com/photo/109919/download/?search_query=&tracking_id=411xe21veam"
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img = np.array(img)
# initialize tensorrt
TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
trt_runtime = trt.Runtime(TRT_LOGGER)
cfx = cuda.Device(0).make_context()
my_function(img) # ok
my_function(img) # ok
# ----- TENSORRT ---------
cfx.push()
# .... tensorrt inference....
cfx.pop()
# ----- TENSORRT ---------
my_function(img) # <---- error
I even tried to do it other ways, but unfortunately with the same result:
cfx.push()
my_function(img) # ok
cfx.pop()
cfx.push()
my_function(img) # error
cfx.pop()
#admin: if you can think of a better name for this question feel free to edit it :)
There were multiple contexts open. For instance, it seems that all of the following open a context:
import pycuda.autoinit
cfx.cuda.Device(0).make_context()
cfx.push()
So if you run the three command above, then simply running one cfx.pop() won't be enough. You will need to run cfx.pop() three times to pop all the contexts.
I am using Pytesseract in python, to recognize only numbers of 1, 2 and 3 digits, (any) in a screenshot of the screen, but sometimes it is conjugated to numbers with letters, (a = 4) which is a problem. I think the numbers are very smallis the number in screenshot
import pytesseract
from PIL import Image
import cv2
import pyautogui
pytesseract.pytesseract.tesseract_cmd =r"C:\Users\Lenovo\AppData\Local\Tesseract-
OCR\tesseract.exe"
while True:
answer2 = pyautogui.screenshot("answer2.png",region=(456, 51, 28, 14))
im = cv2.imread("answer2.png",1)
answer2 = pytesseract.image_to_string(Image.fromarray(im), config="--psm 6")
answer2=float(answer2)
print(answer2)
Hi i want to overlay or paste an image on bigger images(have a folder containinf 10 images and want to overlay the smaller images on all 10) and save them in a different folder. I did try somethings but ran into errors.
import scipy.misc
import numpy as np
import os
import cv2
outPath = "C:\darkflow\Augmented Images\augmented_images\.."
cov = cv2.imread("C:\darkflow\Augmented Images\extracted\cover\extracted_cover.jpg")
bgs = [cv2.imread(file) for file in glob.glob("C:\darkflow\Augmented Images\images\*.jpg")]
for bg in bgs:
bg[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = cov
f_image = cv2.cvtColor(bg, cv2.COLOR_BGR2RGB)
fullpath = os.path.join(outPath, 'augmented_'+ bg)
misc.imsave(fullpath, f_image)
with this code i get an error : ufunc 'add' did not contain a loop with signature matching types dtype('
I found the answer while looking into the code. My code is
from scipy import ndimage, misc
import scipy.misc
import numpy as np
import os
import cv2
cov = cv2.imread("C:\darkflow\Augmented Images\extracted\cover\extracted_cover.jpg")
bgs = [cv2.imread(file) for file in glob.glob("C:\darkflow\Augmented Images\images\*.jpg")]
d=1
x_offset=100
y_offset= 100
for bg in bgs:
bg[y_offset:y_offset+ cov.shape[0], x_offset:x_offset+ cov.shape[1]] = cov
filename = "images/file_%d.jpg"%d
cv2.imwrite(filename, bg)
d+=1
I literally copy and pasted the example of how to use the hover tool from bokeh's documentation and I still can't get this damn thing to work. I just want bokeh's hover tool to display the x and y coordinates. I think I've implemented it correctly but let me know if anything's wrong. (The ASCII file reads in flawlessly and the graph plots correctly and all the other tools work)
from bokeh.plotting import *
from bokeh.objects import HoverTool
from collections import OrderedDict
output_notebook()
%matplotlib inline
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import mpld3
from mpld3 import plugins, utils
mpld3.enable_notebook()
from pylab import *
import pandas as pd
chip1 = pd.io.parsers.read_table("Chip1_Buffer_ASCII", sep=";")
chip2 = pd.io.parsers.read_table("Chip2_Buffer_ASCII", sep=";")
chip3 = pd.io.parsers.read_table("Chip3_Buffer_ASCII", sep=";")
chip1_1=chip1
chip1_2=chip2
chip1_3=chip3
chip1_1["Frequency (Hz)"]=chip1["Frequency (Hz)"].map(lambda x: math.log10(x))
chip1_2["Frequency (Hz)"]=chip2["Frequency (Hz)"].map(lambda x: math.log10(x))
chip1_3["Frequency (Hz)"]=chip3["Frequency (Hz)"].map(lambda x: math.log10(x))
diff_1_2 = chip1 - chip2
diff_1_2["Frequency (Hz)"] = chip1_1["Frequency (Hz)"]
source1 = ColumnDataSource(chip1_1.to_dict("list"))
source2 = ColumnDataSource(chip1_2.to_dict("list"))
source3 = ColumnDataSource(chip1_3.to_dict("list"))
source4=ColumnDataSource(diff_1_2.to_dict("list"))
import bokeh.plotting as bk
bk.figure(plot_width=600, # in units of px
plot_height=600,
title="Hello World!",
tools="pan,wheel_zoom,box_zoom,select,reset,hover")
bk.hold()
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source1,logx=True,color="red",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source2,logx=True,color="green",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source3,logx=True,color="orange",xlim=[0, 10000])
bk.line("Frequency (Hz)", "-Phase (°)",line_width=2,source=source4,logx=True,color="orange",xlim=[0, 10000])
hover = bk.curplot().select(dict(type=HoverTool))
hover.tooltips=OrderedDict([
("(x,y)", "($x, $y)"),
("index", "$index")
])
bk.show()