Game bot error (python chrome dinousor game error) - python

I followed a tut Click me! and i get un-expected results: my code
from PIL import ImageGrab, ImageOps
import pyautogui
import time
from numpy import *
class Cordinates():
replayBtn = (960,355)
dinosaur = (784,375)
#770x360, 770x365
def restartGame():
pyautogui.click(Cordinates.replayBtn)
def pressSpace():
pyautogui.keyDown('space')
time.sleep(0.05)
print("Jump")
pyautogui.keyUp('space')
def imageGrab():
box = (Cordinates.dinosaur[0]+435, Cordinates.dinosaur[1]+25,
Cordinates.dinosaur[1]+335, 10)
image = ImageGrab.grab(box)
grayImage = ImageOps.grayscale(image)
a = array(grayImage.getcolors())
return a.sum()
def main():
restartGame()
while True:
if imageGrab()!=1447:
#pressSpace()
print(imageGrab)
time.sleep(0.1)
time.sleep(2)
main()
and the print i added for debug gives me
<function imageGrab at 0x079CBD68>
What can i fix to make this work?

here
if imageGrab()!=1447:
#pressSpace()
print(imageGrab)
time.sleep(0.1)
you print(imageGrab) like variable but you need to print like method
print(imageGrab())
you printed out a function, not a result of a function

Related

after using pyinstaller to convert py to exe it doesn't work

I want to monitor one area but after converting it doesn't work.
There is no message when I used cmd to find some error.
when I start it, it just blink few minutes and then black out.
It work well in python.
please help.
here is the code.
import multiprocessing
from re import A
from PIL import Image
import pytesseract
import time
import threading
from PIL import ImageGrab
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
import pyautogui
import keyboard
import winsound
from multiprocessing import Process
def screenshot():
pyautogui.screenshot("C:\\Users\\youngseb\\Desktop\\screenshot1.png", region = region1)
img1 = Image.open("C:\\Users\\youngseb\\Desktop\\screenshot1.png")
A1 = pytesseract.image_to_string(img1,lang='kor+eng')
#print(T)
strings = A1.split()
print(strings)
time.sleep(5)
pyautogui.screenshot("C:\\Users\\youngseb\\Desktop\\screenshot1.png", region = region1)
img1 = Image.open("C:\\Users\\youngseb\\Desktop\\screenshot1.png")
A2 = pytesseract.image_to_string(img1,lang='kor+eng')
strings = A2.split()
print(strings)
if (A1 == A2):
winsound.Beep(2000,500)
print("ERROR")
else :
time.sleep(0.5)
threading.Timer(5, screenshot).start()
if __name__ == '__main__' :
P1 = Process(target=screenshot)
P1.start()
P1.join()
region1 = (572,333,35,15)

Pytesseract really slow

so I'm trying to read out text from MS Teams and use that text to make inputs on the keyboard.
Right now, I work with the threading module to have one thread for the input and one thread for the image_to_string. Following is the function for the image_to_string.
def imToString():
global message
print("Image getting read")
pytesseract.pytesseract.tesseract_cmd ='C:\\Users\\gornicec\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'
while(True):
print("preIMGgrab")
cap = ImageGrab.grab(bbox=(177, 850, 283, 881))
grayCap = cv2.cvtColor(np.array(cap), cv2.COLOR_BGR2GRAY)
print("postIMGgrab")
t = time.perf_counter()
print("preMSG" + str(t))
message = pytesseract.image_to_string(
grayCap,
lang ='deu',config='--psm 6')
print(str(message) + "was read" + str(time.perf_counter() - t))
I don't know how but it takes about 8 seconds to read an image thats 1000 pixels big. I need this to be at highest 2 seconds. I'll add the whole code at the end. If there is any way to make it faster or to do it differently please tell me so.
WHOLE CODE:
import numpy as np
import time
import pytesseract
from win32gui import GetWindowText, GetForegroundWindow
import win32api
import cv2
import pyautogui
from PIL import ImageGrab
import threading
from ahk import AHK
import keyboard
message = ""
ahk = AHK(executable_path='C:\\Program Files\\AutoHotkey\\AutoHotkey.exe')
def Controls():
global message
while True:
booleanVal = True
if booleanVal:
#imToString()
print("message")
#print("rechts" in message.lower())
#print(f'LĂ„NGE: {len(message)}')
if "vorne" in message.lower():
# Control(message, 'w')
ahk.key_press('w')
#message = ""
if "hinten" in message.lower():
# Control(message, 's')
ahk.key_press('s')
#message = ""
if "links" in message.lower():
# Control(message, 'a')
ahk.key_press('a')
#message = ""
if "rechts" in message.lower():
# Control(message, 'd')
#print("HAHAHA")
ahk.key_press('d')
#message = ""
if "greif" in message.lower():
ahk.key_press('space')
#message = ""
time.sleep(0.5)
#IMGTOSTRING---
controls = threading.Thread(target=Controls)
controls.start()
grab = threading.Thread(target=imToString)
grab.start()
pytesseract is not suit for large amount of images or images that are already in memory, its write them to a file and then pass the file path to tesseract cli, if you want to improve the performance of you script try using library that works directly with tesseract api.
like this: https://pypi.org/project/tess-py-api/

What do I do when I use the pillow module to take one screenshot and it takes several instead?

I am trying to take several screeenshots with Python each time I press the key 'p' on my keyboard, with the page number being updated with each new screenshot. However, the program ends up taking several screenshots with each press of the key.
from PIL import ImageGrab
import keyboard
def shot(number):
while True:
if keyboard.is_pressed('p'):
image = ImageGrab.grab(bbox=(580, 0, 1340, 1080))
image.save(f"{number} page.pdf")
shot(number + 1)
else:
pass
for i in range(1, 2):
shot(i)
from PIL import ImageGrab
import keyboard
def shot(number):
while True:
if keyboard.is_pressed('p'):
image = ImageGrab.grab(bbox=(580, 0, 1340, 1080))
image.save(f"{number} page.pdf")
shot(number + 1)
break #to break loop
else:
pass
for i in range(1, 2):
shot(i)
The problem is recursion you use, you call it right after you take screen, try this:
from PIL import ImageGrab
import keyboard
import time
def shot(number):
while True:
if keyboard.is_pressed('p'):
image = ImageGrab.grab(bbox=(580, 0, 1340, 1080))
image.save(f"{number} page.pdf")
break
else:
pass
i=1
while True:
shot(i)
#suspend for a second, so we don't take another screen immediately
time.sleep(1)
i+=1
But there is way simpler method, you don't need to use loops if you use keyboard.wait, which is also way more efficient.
Also to avoid memory consumption we can get rid of recursion with a simple loop:
from PIL import ImageGrab
import keyboard
import time
def shot(number):
keyboard.wait("p")
image = ImageGrab.grab(bbox=(580, 0, 1340, 1080))
image.save(f"{number} page.pdf")
time.sleep(1)
i=1
while True:
shot(i)
i+=1

python, cv2.imshow(), raspberryPi and a black screen

Currently trying write code with a GUI which will allow for toggling on/off image processing. Ideally the code will allow for turning on/off window view, real time image processing (pretty basic), and controlling an external board.
The problem I'm having revolves around the cv2.imshow() function. A few months back I made a push to increase processing rates by switching from picamera to cv2 where I can perform more complex computations like background subtraction without having to call python all the time. using the bcm2835-v4l2 package, I was able to pull images directly from the picamera using cv2.
fast forward 6 months and while trying to update the code, I find that the function cv2.imshow() does not display correctly anymore. I thought it might be a problem with bcm2835-v4l2 but tests using matplotlib show that the connection is fine. it appears to have everything to do with cv2.imshow() or so I guess.
I am actually creating a separate thread using the threading module for image capture and I am wondering if this could be the culprit. I don't think so though as typing in the commands
import cv2
camera = cv2.VideoCapture(0)
grabbed,frame = camera.read()
cv2.imshow(frame)
produces the same black screen
Down below is my code I am using (on the RPi3) and some images show the error and what is expected.
as for reference here are the details about my system
Raspberry pi3
raspi stretch
python 3.5.1
opencv 3.4.1
Code
import cv2
from threading import Thread
import time
import numpy as np
from tkinter import Button, Label, mainloop, Tk, RIGHT
class GPIOControllersystem:
def __init__(self,OutPinOne=22, OutPinTwo=27,Objsize=30,src=0):
self.Objectsize = Objsize
# Build GUI controller
self.TK = Tk() # Place TK GUI class into self
# Variables
self.STSP = 0
self.ShutdownVar = 0
self.Abut = []
self.Bbut = []
self.Cbut = []
self.Dbut = []
# setup pi camera for aquisition
self.resolution = (640,480)
self.framerate = 60
# Video capture parameters
(w,h) = self.resolution
self.bytesPerFrame = w * h
self.Camera = cv2.VideoCapture(src)
self.fgbg = cv2.createBackgroundSubtractorMOG2()
def Testpins(self):
while True:
grabbed,frame = self.Camera.read()
frame = self.fgbg.apply(frame)
if self.ShutdownVar ==1:
break
if self.STSP == 1:
pic1, pic2 = map(np.copy,(frame,frame))
pic1[pic1 > 126] = 255
pic2[pic2 <250] = 0
frame = pic1
elif self.STSP ==1:
time.sleep(1)
cv2.imshow("Window",frame)
cv2.destroyAllWindows()
def MProcessing(self):
Thread(target=self.Testpins,args=()).start()
return self
def BuildGUI(self):
self.Abut = Button(self.TK,text = "Start/Stop System",command = self.CallbackSTSP)
self.Bbut = Button(self.TK,text = "Change Pump Speed",command = self.CallbackShutdown)
self.Cbut = Button(self.TK,text = "Shutdown System",command = self.callbackPumpSpeed)
self.Dbut = Button(self.TK,text = "Start System",command = self.MProcessing)
self.Abut.pack(padx=5,pady=10,side=RIGHT)
self.Bbut.pack(padx=5,pady=10,side=RIGHT)
self.Cbut.pack(padx=5,pady=10,side=RIGHT)
self.Dbut.pack(padx=5,pady=10,side=RIGHT)
Label(self.TK, text="Controller").pack(padx=5, pady=10, side=RIGHT)
mainloop()
def CallbackSTSP(self):
if self.STSP == 1:
self.STSP = 0
print("stop")
elif self.STSP == 0:
self.STSP = 1
print("start")
def CallbackShutdown(self):
self.ShutdownVar = 1
def callbackPumpSpeed(self):
pass
if __name__ == "__main__":
GPIOControllersystem().BuildGUI()
Using matplotlib.pyplot.imshow(), I can see that the connection between the raspberry pi camera and opencv is working through the bcm2835-v4l2 connection.
However when using opencv.imshow() the window result in a blackbox, nothing is displayed.
Update: so while testing I found out that when I perform the following task
import cv2
import matplotlib
camera = cv2.VideoCapture(0)
grab,frame = camera.read()
matplotlib.pyplot.imshow(frame)
grab,frame = camera.read()
matplotlib.pyplot.imshow(frame)
update was solved and not related to the main problem. This was a buffering issue. Appears to have no correlation to cv2.imshow()
on a raspberry you should work with
from picamera import PiCamera
checkout pyimagesearch for that

Python wrong multiple output

I have a func that retrieve information from program. It point the mouse grab an image, resize it, then get recognized with tesseract and add to ValueIndex.
from PIL import Image
import pytesseract
import pyscreenshot as ImageGrab
from pynput.mouse import Button, Controller
import re
def GetValues(): #Read matrix of digit from
pytesseract.pytesseract.tesseract_cmd ='C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'
mouse = Controller()
Mul=2
ValueIndex=[0 for i in range(0,170)] # Results
y1=163
if __name__ == "__main__":
for j in range(0,1):# get 1 line for example
y1=y1+67
x1=1350
for i in range(0,13):
x1=x1+67
mouse.position = (x1, y1)
mouse.press(Button.left)
mouse.release(Button.left)
im=ImageGrab.grab(bbox=(1485, 1112,1680, 1177))
x,y = im.size
x=x*Mul
y=y*Mul
size=x,y
im_resized = im.resize(size, Image.ANTIALIAS) # resize for tesseract
im_resized.save('test%s.png' % i)
data = pytesseract.image_to_string(im_resized)
q=''.join(re.findall('\d',data)) # gt digits from str
if (len(q)==4):
q=indexq[:2]+'.'+q[2:]
if len(q)==3:
q=q[:1]+'.'+q[1:]
GetInd=j*13+i+1
ValueIndex[GetInd]=float(q)
print(i,' ',data,' ',ValueIndex[GetInd]) # print to see the progress
return(ValueIndex)
GetValues() #When i comment it, print only 1 time
print('Why so many times?:)')
It work properly, but when i add print in body of prorgam it output multiple times. It's not in func loop, whats wrong?
Why so many times?:)
0 +9.76% 9.76
Why so many times?:)
1 +619% 6.19
Why so many times?:)
2 +5.36% 5.36
and so on

Categories

Resources