Hey i am trying to locate an image but get this error on why i use the value as (any,any,250,250) but doesnt show the error when i use(any,any,350(more than 350),250(more than 250))
here is my code
`
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
import cv2
import numpy as np
PlayerOnRight = False
PlayerOnFullRight = False
PlayerOnFullLeft = False
PlayerOnLeft = False
PlayerOnMiddle = False
while 1:
if PlayerOnMiddle == True and pyautogui.locateOnScreen('player.png', region=(1080,600,800,200), confidence=0.7) != None:
print("Right Side")
time.sleep(0.5)
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
print("Left Side")
time.sleep(0.5)
`
here is the error
`Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Pyhton_bot\test.py", line 20, in <module>
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 213, in locateOnScreen
return pyscreeze.locateOnScreen(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 373, in locateOnScreen
retVal = locate(image, screenshotIm, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 353, in locate
points = tuple(locateAll(needleImage, haystackImage, **kwargs))
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 219, in _locateAll_opencv
raise ValueError('needle dimension(s) exceed the haystack image or region dimensions')
ValueError: needle dimension(s) exceed the haystack image or region dimensions
`
i expted it to work noramlly to locate image and pint the given text but got this error
please help me fix this
Because the region has to be bigger than your player.png image. Either crop your player.png image or increase the region size
Related
I am making a bot that makes the chrome dinosaur jump every time it sees a cactus.
The RGB for the cactus is (83,83,83)
I made a specific coordinate for my code to look at, and check if the RGB of that pixel matches the cactus (jump_place)
However, when I run it, it works for about 2 seconds, and then gives me this error:
Traceback (most recent call last):
File "c:\Users\dofia\OneDrive\Desktop\coding VS\Other Projects\DINO BOT\tempCodeRunnerFile.py", line 29, in <module>
if pyautogui.pixel(810, 635)[0] == 83:
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 584, in pixel
return (r, g, b)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 124, in __exit__
next(self.gen)
File "C:\Users\dofia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pyscreeze\__init__.py", line 113, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
Here is my code:
from pyautogui import *
import pyautogui
import time
import keyboard
import random
time.sleep(3)
replay = (1127,591)
jump_place = (866,630)
def restart():
pyautogui.click(replay)
def jump():
pyautogui.keyDown('space')
time.sleep(0.5)
print("Jump!")
pyautogui.keyUp('space')
restart()
while keyboard.is_pressed('p') == False:
if pyautogui.pixel(810, 635)[0] == 83:
jump()
Is there anything I am doing wrong?
The link to the dinosaur game is: http://www.trex-game.skipser.com/
I am trying to iterate over the pixels of an image, more specifically a screenshot i'm acquiring via ImageGrab module. Here's my code:
from PIL import ImageGrab as ig
import numpy as np
from pynput.mouse import Controller
from pynput.keyboard import Key
from pynput import keyboard
mouse= Controller()
def onpress(key):
try:
pressed_key= key.char
except AttributeError:
pressed_key= str(key)[4:]
if pressed_key == 'esc':
print('Quitting process')
return False
elif pressed_key == 'space':
mousepos= mouse.position
pic= ig.grab()
arr= np.array(pic)
print(f'Pixel color at {mousepos}: RGB{arr[mousepos]}')
# here the error is raised
with keyboard.Listener(on_press= onpress) as listener:
listener.join()
I want to inspect the RGB color of the pixel at the mouse position when the spacebar is pressed. It works fine for the "top-left-most" pixels, here are some output examples:
1) Pixel color at (150, 193): RGB[242 243 244]
2) Pixel color at (579, 302): RGB[0 0 0]
3) Pixel color at (887, 108): RGB[145 89 4]
but when I move the mouse slightly at the bottom-right of the screen (from the center just a little bit bottom-right) it raises an error like this:
Traceback (most recent call last):
File "imagegrab.py", line 64, in <module>
listener.join()
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 199, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\marca\Anaconda3\lib\site-packages\six.py", line 692, in reraise
raise value.with_traceback(tb)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
return f(self, *args, **kwargs)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
self.on_press(key)
File "C:\Users\marca\Anaconda3\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
if f(*args) is False:
File "imagegrab.py", line 42, in onpress
print(f'{count}) Pixel color at {mousepos}: RGB{arr[mousepos]}')
IndexError: index 1152 is out of bounds for axis 0 with size 1080
This error IS NOT raised if I load the image using
pixels= pic.load()
print(f'{count}) Pixel color at {mousepos}: RGB{pixels[mousepos]}')
which works perfectly (here I was pointing at the top-left and bottom-right corners of the screen):
1) Pixel color at (0, 0): RGB(56, 36, 12)
2) Pixel color at (1914, 1016): RGB(22, 15, 5)
I think it has something to do with my laptop's screen DPI, as previously I had to apply a fix that was suggested in this Github thread, as I was having this kind of screen-capture problem.
The array index shown in the error (1152), as you can see, overflows the common 1920x1080 resolution of HD screens. I have no clue in what to do to fix this, so I hope I've been clear and somebody can help me.
So I am trying to create a Python Program to detect similar details in two images using Python's OpenCV. I have the two images and they are in my current directory, and they exist (see the code in lines 6-17). But I am getting the following error when I try running it.
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
path1 = "WIN_20171207_13_51_33_Pro.jpg"
path2 = "WIN_20171207_13_51_43_Pro.jpg"
if os.path.isfile(path1):
img1 = cv2.imread('WIN_20171207_13_51_33_Pro.jpeg',0)
else:
print ("The file " + path1 + " does not exist.")
if os.path.isfile(path2):
img2 = cv2.imread('WIN_20171207_13_51_43_Pro.jpeg',0)
else:
print ("The file " + path2 + " does not exist.")
orb = cv2.ORB_create()
kpl1, des1 = orb.detectAndCompute(img1,None)
kpl2, des2 = orb.detectAndCompute(img2,None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x:x.distance)
img3 = cv2.drawMatches(img1,kpl1,img2,kpl2,matches[:10],None, flags=2)
plt.imshow (img3)
plt.show()
Here is the error I keep on getting...
Traceback (most recent call last):
File "C:\Users\jweir\source\repos\BruteForceFeatureDetection\BruteForceFeatureDetection\BruteForceFeatureDetection.py", line 31, in <module>
plt.imshow (img3)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow
**kwargs)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
return func(ax, *args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow
im.set_data(X)
File "C:\Program Files\Python36\lib\site-packages\matplotlib\image.py", line 600, in set_data
raise TypeError("Image data cannot be converted to float")
TypeError: Image data cannot be converted to float
Can someone please explpain to me why I am getting this error, what it means, and how to fix it.
You're not actually reading in an image.
Check out what happens if you try to display None in matplotlib:
plt.imshow(None)
Traceback (most recent call last):
File ".../example.py", line 16, in <module>
plt.imshow(None)
File ".../matplotlib/pyplot.py", line 3157, in imshow
**kwargs)
File ".../matplotlib/__init__.py", line 1898, in inner
return func(ax, *args, **kwargs)
File ".../matplotlib/axes/_axes.py", line 5124, in imshow
im.set_data(X)
File ".../matplotlib/image.py", line 596, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
You're reading WIN_20171207_13_51_33_Pro.jpeg but you're checking if WIN_20171207_13_51_33_Pro.jpg exists. Note the different extensions. Why do you have the filename written twice (and differently)? Just simply write:
if os.path.isfile(path1):
img1 = cv2.imread(path1, 0)
else:
print ("The file " + path1 + " does not exist.")
Note that even if you put a bogus file into cv2.imread(), the resulting image will just be None, which doesn't error in any of the subsequent function calls until matplotlib tries to draw it. If you print(img1) after reading, you'll see it's None and not reading properly.
I do not know whether it is relevant with your case but since we assigning the file path in string type like cv2.imread("filepathHere"), if arguments like "\b" or "\r" occurs in the file path it causes program to pop an error such as this.
When I encountered such an error before, I changed the file name from file / brick.png to ibrick.png and the problem was resolved.
I'm trying to run the following code,
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
for index,data in enumerate(skeleton):
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
head=data.SkeletonPositions[JointId.Head]
print head
but Kinect shuts down and gives the following error:
Traceback (most recent call last):
File "C:\Users\sayyed javed ahmed\Desktop\Humaira\Practice Codes-Python\skeletonnew.py", line 5, in <module>
with nui.Runtime() as kinect:
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 126, in __init__
self.camera = Camera(self)
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 352, in __init__
self.elevation_angle
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 359, in get_elevation_angle
return self.runtime._nui.NuiCameraElevationGetAngle()
File "C:\Python27\lib\site-packages\pykinect\nui\_interop.py", line 200, in NuiCameraElevationGetAngle
_NuiInstance._NuiCameraElevationGetAngle(self, ctypes.byref(res))
File "_ctypes/callproc.c", line 950, in GetResult
WindowsError: [Error -2147024883] The data is invalid
I'm new to PyKinect so any help is appreciated! Thanks!
Firstly, there are typos in your code. You're assigning a callback to skeleton_frame_ready function in kinect.skeleton_frame_ready+=skeleton_frame_ready, but have defined it as def skeleton_fram_raedy(skeleton_frame).
Secondly, I think your indentation is off, you have a function definition in a for loop in a while loop:
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
...
Try something like this:
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
def skeleton_frame_ready(skeleton_frame):
for skeleton in frame.SkeletonData:
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
for index,data in enumerate(skeleton):
head=data.SkeletonPositions[JointId.Head]
print head
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
Thirdly, the error indicates that invalid argument is passed to nui for the kinect camera angle. Not sure why that is. You could try setting the elevation angle to 0 right after initializing nui:
with nui.Runtime() as kinect:
kinect.camera.elevation_angle = 0
kinect.skeleton_frame_ready+=skeleton_frame_ready
I am wondering why I can get this error:
pyglet.lib.gl.GLExeption: invalid value
at: self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
Imported libs:
import sys
import math
import random
import time
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse, Window
from PIL import Image
I'm using PIL for making the PNG:
print "Creating ", TEXTURE_PATH
images = map(Image.open, texture_path)
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.convert('RGB')
new_im.save(TEXTURE_PATH, "PNG")
And the 'texture_path`(lowercase) is here:
texture_path = ['res/textures/grass_top.png'] * 99
The full error message is:
Traceback (most recent call last):
File "D:\pythoncode\pyglet\minecraft_remake.py", line 955, in <module>
main()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 948, in main
window = Window(width = 640, height = 480, caption="Minecraft 3d!", resizable=True)
File "D:\pythoncode\pyglet\minecraft_remake.py", line 554, in __init__
self.model = Model()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 198, in __init__
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 818, in get_texture
force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 803, in create_texture
rectangle, force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 1514, in create
blank)
File "C:\Python27\lib\site-packages\pyglet\gl\lib.py", line 104, in errcheck
raise GLException(msg)
GLException: invalid value
I found the problem, but didn't know how to fix it, the problem are in the PNG making.
When I replace the textures.png with another picture, it's working
but when I make one with PIL, it doesn't work.
Solved: the problem is in my .PNG Editor, i just make the image manually and it works!
im using Graphics Gale Free edition to edit and it will work.
i think the problem is in the PIL itself. Or The pyglet doesnt load PIL config PNG
P.s it may be because color configuration