Python pyautogui.screenshot() Examples
The following are 18
code examples of pyautogui.screenshot().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyautogui
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: OSXUI.py From Poco with Apache License 2.0 | 6 votes |
def Screenshot(self, width): self.SetForeground() size = self.root.AXSize pos = self.root.AXPosition pyautogui.screenshot('Screenshot.png', (pos[0], pos[1], size[0], size[1])).save('Screenshot.png') f = open(r'Screenshot.png', 'rb') deflated = zlib.compress(f.read()) ls_f = base64.b64encode(deflated) f.close() return [ls_f, "png.deflate"] # self.root.ToBitmap().ToFile('Screenshot.bmp') # f = open(r'Screenshot.bmp', 'rb') # ls_f = base64.b64encode(f.read()) # f.close() # return [ls_f, "bmp"]
Example #2
Source File: screenshot_image.py From iris with Mozilla Public License 2.0 | 6 votes |
def _region_to_image(region) -> Image or ScreenshotError: # On Linux, try to use pyautogui to take screenshots, and revert to mss if it fails. # On Windows/Mac, do the reverse. try: if OSHelper.is_linux(): try: grabbed_area = _pyautogui_screenshot(region) except ScreenshotError as e: logger.debug(e) grabbed_area = _mss_screenshot(region) else: try: grabbed_area = _mss_screenshot(region) except ScreenshotError as e: logger.debug(e) grabbed_area = _pyautogui_screenshot(region) except ScreenshotError as e: logger.error("Screenshot failed: %s" % e) raise ScreenshotError("Cannot create screenshot: %s" % e) return grabbed_area
Example #3
Source File: screenshot_image.py From iris with Mozilla Public License 2.0 | 6 votes |
def _pyautogui_screenshot(region): try: return np.array( screenshot(region=(region.x, region.y, region.width, region.height)) ) except (IOError, OSError): raise ScreenshotError("Call to pyautogui.screenshot failed.")
Example #4
Source File: tools.py From Dindo-Bot with MIT License | 6 votes |
def screen_game(region, save_to=None): x, y, width, height = region try: raw = root.get_image(x, y, width, height, X.ZPixmap, 0xffffffff) if hasattr(Image, 'frombytes'): # for Pillow screenshot = Image.frombytes('RGB', (width, height), raw.data, 'raw', 'BGRX') else: # for PIL screenshot = Image.fromstring('RGB', (width, height), raw.data, 'raw', 'BGRX') if save_to is not None: screenshot.save(save_to + '.png') except: filename = save_to + '.png' if save_to is not None else None screenshot = pyautogui.screenshot(filename, region) return screenshot # Return pixel color of given x, y coordinates
Example #5
Source File: imagesearch.py From python-imagesearch with MIT License | 6 votes |
def imagesearch_count(image, precision=0.9): img_rgb = pyautogui.screenshot() if is_retina: img_rgb.thumbnail((round(img_rgb.size[0] * 0.5), round(img_rgb.size[1] * 0.5))) img_rgb = np.array(img_rgb) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(image, 0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) loc = np.where(res >= precision) count = 0 for pt in zip(*loc[::-1]): # Swap columns and rows # cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2) // Uncomment to draw boxes around found occurrences count = count + 1 # cv2.imwrite('result.png', img_rgb) // Uncomment to write output image with boxes drawn around occurrences return count
Example #6
Source File: _screenshot.py From robotframework-imagehorizonlibrary with MIT License | 6 votes |
def take_a_screenshot(self): '''Takes a screenshot of the screen. This keyword is run on failure if it is not overwritten when `importing` the library. Screenshots are saved to the current working directory or in the ``screenshot_folder`` if such is defined during `importing`. The file name for the screenshot is the current suite name with a running integer appended. If this keyword is used outside of Robot Framework execution, file name is this library's name with running integer appended. ''' target_dir = self.screenshot_folder if self.screenshot_folder else '' if not isinstance(target_dir, str): raise ScreenshotFolderException('Screenshot folder is invalid: ' '"%s"' % target_dir) path = self._make_up_filename() path = abspath(path_join(target_dir, path)) LOGGER.info('Screenshot taken: {0}<br/><img src="{0}" ' 'width="100%" />'.format(path), html=True) ag.screenshot(path)
Example #7
Source File: FarmBot.py From PUBG-Battlepoint-FarmBot with GNU General Public License v3.0 | 5 votes |
def getpixel(self,x, y): return screenshot().getpixel((x, y))
Example #8
Source File: main.py From python-examples with MIT License | 5 votes |
def find(screenshot): # dictionary for digits grouped by "y" found = dict() # find all digits for digit in range(10): positions = pyautogui.locateAll('digits/{}.png'.format(digit), screenshot, True) for x,y,_,_ in positions: if y not in found: found[y] = dict() found[y][x] = digit # recreate values result = [] for row in sorted(found): cols = sorted(found[row]) value = ''.join(str(found[row][col]) for col in cols) result.append(value) return result
Example #9
Source File: tools.py From Dindo-Bot with MIT License | 5 votes |
def take_window_screenshot(window, save_to='screenshot'): size = window.get_geometry() pb = Gdk.pixbuf_get_from_window(window, 0, 0, size.width, size.height) pb.savev(save_to + '.png', 'png', (), ()) # Return a screenshot of the game
Example #10
Source File: tools.py From Dindo-Bot with MIT License | 5 votes |
def print_internet_state(state=None): if state is None: state = internet_on() return 'Internet is ' + ('on' if state else 'off') # Take a screenshot of given window
Example #11
Source File: _screenshot.py From robotframework-imagehorizonlibrary with MIT License | 5 votes |
def _make_up_filename(self): try: path = BuiltIn().get_variable_value('${SUITE NAME}') path = '%s-screenshot' % path.replace(' ', '') except RobotNotRunningError: LOGGER.info('Could not get suite name, using ' 'default naming scheme') path = 'ImageHorizon-screenshot' path = '%s-%d.png' % (path, self.screenshot_counter) self.screenshot_counter += 1 return path
Example #12
Source File: Screenshot.py From roc with MIT License | 5 votes |
def region_shot(cls,name='seq', seq_id=0, x1=0, y1=0, x2=200, y2=200, color=False, x_val=0): sleep(1) image = pyautogui.screenshot(region=(x1, y1, x2, y2)) if not color: image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY) else: image = cv2.cvtColor(np.array(image), 2) cv2.imwrite('sequential/bw/' + str(name) + str(seq_id) + '.png', image) # process image im = Image.open('sequential/bw/' + str(name) + str(seq_id) + '.png') R, G, B = im.convert('RGB').split() r = R.load() g = G.load() b = B.load() w, h = im.size # Convert non-black pixels to white for i in range(w): for j in range(h): # if(r[i, j] != 0 or g[i, j] != 0 or b[i, j] != 0): if (x_val < r[i, j] < 100 or x_val < g[i, j] < 100 or x_val < b[i, j] < 100): r[i, j] = 0 # g[i, j] = 0 # Just change R channel # Merge just the R channel as all channels im = Image.merge('RGB', (R, R, R)) im.save('sequential/bw/' + str(name) + str(seq_id) + '.png')
Example #13
Source File: imagesearch.py From python-imagesearch with MIT License | 5 votes |
def imagesearch(image, precision=0.8): im = pyautogui.screenshot() if is_retina: im.thumbnail((round(im.size[0] * 0.5), round(im.size[1] * 0.5))) # im.save('testarea.png') useful for debugging purposes, this will save the captured region as "testarea.png" img_rgb = np.array(im) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(image, 0) template.shape[::-1] res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if max_val < precision: return [-1, -1] return max_loc
Example #14
Source File: imagesearch.py From python-imagesearch with MIT License | 5 votes |
def region_grabber(region): if is_retina: region = [n * 2 for n in region] x1 = region[0] y1 = region[1] width = region[2] - x1 height = region[3] - y1 return pyautogui.screenshot(region=(x1, y1, width, height))
Example #15
Source File: screenshot.py From B.E.N.J.I. with MIT License | 5 votes |
def screenshot_win(): try: pic = pyautogui.screenshot() spath = os.path.expanduser('~') + '/Desktop/screenshot.jpg' pic.save(spath) except: print("Unable to take screenshot.")
Example #16
Source File: FarmBot.py From PUBG-Battlepoint-FarmBot with GNU General Public License v3.0 | 5 votes |
def pixelMatchesColor(self, x, y, expectedRGBColor, tolerance=0): pix = self.getpixel(x,y) if len(pix) == 3 and len(expectedRGBColor) == 3: # RGB mode r, g, b = pix[:3] exR, exG, exB = int(expectedRGBColor[0]), int(expectedRGBColor[1]), int(expectedRGBColor[2]) return (abs(r - exR) <= tolerance) and (abs(g - exG) <= tolerance) and (abs(b - exB) <= tolerance) elif len(pix) == 4 and len(expectedRGBColor) == 4: # RGBA mode r, g, b, a = pix exR, exG, exB, exA = expectedRGBColor return (abs(r - exR) <= tolerance) and (abs(g - exG) <= tolerance) and (abs(b - exB) <= tolerance) and ( abs(a - exA) <= tolerance) else: assert False, 'Color mode was expected to be length 3 (RGB) or 4 (RGBA), but pixel is length %s and expectedRGBColor is length %s' % ( len(pix), len(expectedRGBColor)) # def printScreen(message): # if takeScrenshot: # if not os.path.exists(debug_directory): # os.makedirs(debug_directory) # screenshot('{}/{}{}.png'.format(debug_directory, strftime("%m.%d %H.%M.%S", gmtime()), message))
Example #17
Source File: PyLoggy.py From PyLoggy with GNU General Public License v3.0 | 5 votes |
def ScreenShot(): global pics_names import pyautogui def generate_name(): return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7)) name = str(generate_name()) pics_names.append(name) pyautogui.screenshot().save(name + '.png')
Example #18
Source File: Overlay.py From COD-MW-2019-DNN with MIT License | 4 votes |
def task(): last100Image = None lastSecondTimestamp = datetime.utcnow() + timedelta(seconds=1) tickCounter = 0 while 1 == 1: tickCounter += 1 if datetime.utcnow() > lastSecondTimestamp: lastSecondTimestamp = datetime.utcnow() + timedelta(seconds=1) print('Ticks Per Second %d' % tickCounter) tickCounter = 0 # Grab Screen image = pyautogui.screenshot(region=(centerPoint[0] - 100, centerPoint[1] - 100, 200, 200)) if last100Image is None: last100Image = image # Predict prediction = model.predict(np.asarray([np.asarray(image)]) / 255) # Print Result v.set("Enemy Confidence " + str(round(prediction[0][0] * 100)).zfill(3) + '%') predictionPercent = round(prediction[0][0] * 100, 2) r = 0 g = 255 b = 0 if predictionPercent > 1: r = int((255*predictionPercent)/100) g = int(255-((255*predictionPercent)/100)) b = 0 flashLabel.configure(foreground="#%02x%02x%02x" % (r, g, b)) flashLabel.update() if predictionPercent == 100: last100Image = image try: render = ImageTk.PhotoImage(image) img = Label(image=render) img.image = render img.place(x=0, y=100) render2 = ImageTk.PhotoImage(last100Image) img100 = Label(image=render2) img100.image = render2 img100.place(x=896, y=100) except: print('error')