• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pyscreenshot.grab函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyscreenshot.grab函数的典型用法代码示例。如果您正苦于以下问题:Python grab函数的具体用法?Python grab怎么用?Python grab使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了grab函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: funcion_mouse

def funcion_mouse(event,x,y,flags,param):
	global drawing_box
	global box
	if event == cv.CV_EVENT_MOUSEMOVE:
		if drawing_box == True:
			box[2] = x - box[0]
			box[3] = y - box[1]
	elif event == cv.CV_EVENT_LBUTTONDOWN:
		drawing_box = True
		box = [x,y,0,0]
	elif event == cv.CV_EVENT_LBUTTONUP:
		drawing_box = False
		if box[2] < 0:
			box[0] +=box[2]
			box[2] *=-1
		if( box[3]<0):
			box[1] += box[3]
			box[3] *= -1
		cf = [box[0],box[1],box[2],box[3]]
		#fich.write(str(box[0])+' '+str(box[1])+' '+str(box[2])+' '+str(box[3])+'\n')
		fich.write(str(box[0])+'\n')
		fich.write(str(box[1])+'\n')
		fich.write(str(box[0]+box[2])+'\n')
		fich.write(str(box[1]+box[3])+'\n')		
		im=ImageGrab.grab(bbox=(box[0],box[1],box[0]+box[2],box[1]+box[3]))
		im=ImageGrab.grab(bbox=(0, 0, 640, 480))
		im.save('recortada.png')
                print 'coordenadas: '+str(box[0])+', '+str(box[1])+', '+str(box[0]+box[2])+', '+str(box[1]+box[3])
开发者ID:eddypre,项目名称:TrianaVisionProject,代码行数:28,代码来源:Reconocimiento.py


示例2: fold

 def fold(self):
     if self.folded:
         return
     self.folded = 1
     print '-----FOLDING-----'
     time.sleep(0.1)
     m = self.m#{{{
     with open('pokerstars/last_control.json') as f:
         last_control = json.load(f)
     if time.time() - last_control < 1.5:
         return
     xr = round((random.random()-0.5)*50)
     yr = round((random.random()-0.5)*30)
     xp = fold_position[0] + xr
     yp = fold_position[1] + yr
     im = pyscreenshot.grab()
     fold_mark = 0
     while fold_mark == 0:
         for xchange in xrange(-20, 20):
             for ychange in xrange(-20, 20):
                 color = im.getpixel((fold_position[0]+xchange+self.shift[0], fold_position[1]+ychange+self.shift[1]))
                 if color[0] > max(color[1:]) + 30:
                     fold_mark = 1
                     break
         im = pyscreenshot.grab()
     m.click(xp+self.shift[0], yp+self.shift[1])
     with open('pokerstars/last_control.json', 'w') as f:
         last_control = time.time()
         f.write(json.dumps(last_control))#}}}
开发者ID:powerresearch,项目名称:Poker-Bot-Reformed,代码行数:29,代码来源:controller.py


示例3: get_Lbox

def get_Lbox():
    box=(x_pad+359,y_pad+232,x_pad+359+1,y_pad+232+1)#must offset from window
    im=ImageOps.grayscale(ImageGrab.grab(box))
    ImageGrab.grab(box).save(os.getcwd() + '/LBox__' + str(int(time.time())) +'.png', 'PNG')
    a=array(im.getcolors())
    q=int(a.sum())
    print "Lbox\t" + str(q)
    return q
开发者ID:ZAQ922,项目名称:OFDP,代码行数:8,代码来源:Code.py


示例4: run

def run(**args):
	cs=ImageGrab.grab()
	return cs
	filename=time.strftime("%Y-%m-%d-%H:%M:%S")
	ImageGrab.grab().save(filename, "JPEG")
	ss=open(filename, 'rb')
	jk=ss.read(2000000)
	ss.close()
	return str(jk)
开发者ID:sorian123,项目名称:chapter7,代码行数:9,代码来源:ss.py


示例5: run

def run(force_backend, n, to_file, bbox=None):
    print '%-20s' % force_backend,

    f = tempfile.NamedTemporaryFile(suffix='.png', prefix='test')
    filename = f.name
    start = time.time()
    for i in range(n):
        if to_file:
            pyscreenshot.grab_to_file(filename, backend=force_backend)
        else:
            pyscreenshot.grab(bbox=bbox, backend=force_backend)
    end = time.time()
    dt = end - start
    print '%-4.2g sec' % (dt), '(%5d ms per call)' % (1000.0 * dt / n)
开发者ID:lushl9301,项目名称:pyscreenshot,代码行数:14,代码来源:speedtest.py


示例6: grab

    def grab(self, autocrop=True):
        try:
            # first try newer pyscreenshot version
            img = pyscreenshot.grab(
                childprocess=self.pyscreenshot_childprocess,
                backend=self.pyscreenshot_backend,
            )
        except TypeError:
            # try older pyscreenshot version
            img = pyscreenshot.grab()

        if autocrop:
            img = self.autocrop(img)
        return img
开发者ID:LukeMurphey,项目名称:splunk-web-input,代码行数:14,代码来源:smartdisplay.py


示例7: run

def run(force_backend, n, to_file, bbox=None):
    print force_backend,' '*(20-len(force_backend)),

    BackendLoader().force(force_backend)
        
    f = tempfile.NamedTemporaryFile(suffix='.png', prefix='test')
    filename=f.name
    start = time.time()
    for i in range(n):
        if to_file:
            pyscreenshot.grab_to_file(filename)
        else:
            pyscreenshot.grab(bbox=bbox)
    end = time.time()
    print int(10*(end - start))/10.0, 'sec'
开发者ID:hejibo,项目名称:pyscreenshot,代码行数:15,代码来源:speedtest.py


示例8: takeSnap

 def takeSnap(self,event=None,force=False):
     if self.lock:
         print "locked",event.type
     while self.lock:
         pass
     self.lock = True
     if not event.button:
         event.x = self.mousex
         event.y = self.mousey
         event.button = self.buttonHold
             
     now = time.time()
     if event.type=='press' and event.button and self.lastEvent and self.lastEvent.button:
         self.autodelay = 0.25
         if event.time-self.lastEvent.time<0.25:
             self.lastEvent.double = True
     if event.type=='release':
         self.autodelay = 0.5
         
     if force or (self.snapOn and S.buttonHold and now-self.lastCall>0.25):
         aw = self.getActiveWindow()
         img = ImageGrab.grab()
         self.timeline.append(dict(timestamp=time.time(),event=event,image=img,active=aw))
         if event.type != 'timed':
             self.lastCall = now
     if event.button and event.type=='press':
         self.lastEvent = event
     self.lock = False
开发者ID:orochvilato,项目名称:tutorial-builder,代码行数:28,代码来源:test.py


示例9: _saveSnapshot2

 def _saveSnapshot2(self):
     scene = str(self.scene)
     im=ImageGrab.grab(bbox=(10,10,510,510)) # X1,Y1,X2,Y2
     if not os.path.isdir(self.image_dir+scene+'/'):
         os.makedirs(self.image_dir+scene)
     if os.path.isfile(self.image_dir+scene+'/data.txt'):
         os.remove(self.image_dir+scene+'/data.txt')
开发者ID:OMARI1988,项目名称:robot_simulation,代码行数:7,代码来源:robot_functions.py


示例10: GetStatusValues

 def GetStatusValues(self, bar):
     img = np.array(ImageGrab.grab().convert('HSV')).astype(np.uint8)
     roi = img[bbox[0][1]:bbox[1][1], bbox[0][0]:bbox[1][0]]
     
     boundaries = [
         ([50, 100, 100], [65, 255, 255]),
         ([140, 150, 120], [150, 255, 255]),
         ([10, 150, 150], [20, 255, 255])
     ]
     
     if bar == 'health':
         (lower,upper)=boundaries[0]
     elif bar == 'thirst':
         (lower,upper)=boundaries[1]
     elif bar == 'hunger':
         (lower,upper)=boundaries[2]
     else:
         (lower,upper)=boundaries[0]
     
     lower = np.array(lower, dtype = "uint8")
     upper = np.array(upper, dtype = "uint8")
         
     mask = cv2.inRange(roi, lower, upper)
     output = cv2.bitwise_and(roi, roi, mask = mask)
     
     h,s,v = cv2.split(output)
     return cv2.countNonZero(v)
开发者ID:terminull,项目名称:RustHP,代码行数:27,代码来源:main.py


示例11: __call__

 def __call__(self, active, pressed=[]):
     if (74, 0) in pressed: # J
         pos, size = self.window.get_frame()
         x_offset = 10
         y_offset = 40
         im = ImageGrab.grab(bbox=(pos[0] + x_offset, pos[1] + y_offset, size[0] + pos[0] + x_offset, size[1] + pos[1] + y_offset - 4))
         im.save(self.file_name)
开发者ID:keksnicoh,项目名称:opengl_plot_prototype,代码行数:7,代码来源:app.py


示例12: waiting_for_fish

 def waiting_for_fish(self):
     time.clock()
     tolerance = t = 5
     while True:
         splash = (156, 150, 135)
         density = []
         image = img.grab()
         colors = set()
         cursor_position = win32api.GetCursorPos()
         x1, y1 = cursor_position[0], cursor_position[1]
         a = (x1 - 50, x1)
         b = (y1 - 25, y1 + 25)
         # time.clock()
         for x in range(a[0], a[1]):
             for y in range(b[0], b[1]):
                 # self.after(1, win32api.SetCursorPos((x, y)))
                 colors.add(image.getpixel((x, y)))
         for i in colors:
             if abs(splash[0] - i[0] <= t):
                 if abs(splash[1] - i[1] <= t):
                     if abs(splash[2] - i[2] <= t):
                         density.append(i)
         print('density length is', len(density))
         if len(density) > 100:
             pyautogui.rightClick()
             return self.start_scan()
         #print(time.clock())
         #print(colors)
         #print(len(colors))
         time.sleep(0.5)
         if time.clock() > 18:
             return self.start_scan()
     return self.start_scan()
开发者ID:ucshadow,项目名称:Fish_bot,代码行数:33,代码来源:even+more.py


示例13: take_screenshot

    def take_screenshot(self,*args):
        global img_screenshot, once
        # switch to stop screenshot button from snaping a shot while snapping a shot
        self.taking_screenshot = True

        # switch to always display the screenshot as original everytime
        once = True

        # makes sure method 'show_changes' takes screenshot instead of img file
        self.img_path = 'screenshot'
        # initializes coords for screenshot
        x1 = None
        y1 = None
        x2 = None
        y2 = None
        
        # starts a cound down timer of 3 seconds, parallel to the for loop
        screenshot_timer_thread = Thread(target=self.screenshot_timer_lbl_update)
        screenshot_timer_thread.start()
        for i in xrange(2):
            for _ in xrange(3):
                time.sleep(1)
            # Parses output for x and y coords
            coords = check_output(['xdotool','getmouselocation','--shell'])
            fo = coords.find("=")
            so = coords.find("Y")
            to = coords.find("S")
           # sets the first point of screenshot 
            if i == 0:
                x1 = int(coords[fo+1:so])
                y1 = int(coords[so+2:to])
           # sets the second point of screenshot 
            else:
                x2 = int(coords[fo+1:so])
                y2 = int(coords[so+2:to])
        # screenshot taken here with the grabbed coordinates
        try:
            screenshot = grab(bbox=(x1,y1,x2,y2))
            screenshot = np.array(screenshot)
        except:
            print("Could not capture image")
            return
        # converts the PIL image format to opencv2 image format
        img_screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
        # printing image array, by taking another screenshot and processing, effects will now show
        try:
            if args[0] == 'array':
                self.taking_screenshot = False
                return img_screenshot
        except:
            pass

        # resizes image if higher than 300px in width or height
        img_screenshot = self.resize_image(img_screenshot)

        # this just makes sure the image shows up after opening it
        self.low_hue.set(self.low_hue.get()+1)
        self.low_hue.set(self.low_hue.get()-1)
        # switch to allow for next screenshot
        self.taking_screenshot = False
开发者ID:jjvilm,项目名称:tools,代码行数:60,代码来源:canny_edge_finder.py


示例14: shoot

def shoot(x1,y1,x2,y2, *args, **kwargs):
    """Takes screenshot at given coordinates as PIL image format, the converts to cv2 grayscale image format and returns it"""
    # PIL format as RGB
    im = pyscreenshot.grab(bbox=(x1,y1,x2,y2)) #X1,Y1,X2,Y2
    #im.save('screenshot.png')

    # Converts to an array used for OpenCV
    im = np.array(im)
    # Next line needs to be taken out, messes up the array order when 
    # looking for hsv values
    #cv_img = im.astype(np.uint8)
    # Converts to BGR format for OpenCV
    cv_img = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
    try:
        if args[0] == 'hsv':
            hsv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2HSV)
            return hsv_img
    except:
        pass
        
    # have to convert from bgr to rgb first for next line 

    cv_gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)

    #Saves image
    #cv2.imwrite('test1.png', cv_gray) ##to save img in cv2

    # Shows Image
    #cv2.imshow('Screenshot', cv_gray)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()
    
    return cv_gray
开发者ID:jjvilm,项目名称:elmacro,代码行数:33,代码来源:Screenshot.py


示例15: get_colors_from_screen

    def get_colors_from_screen(self):
        """
        * Reset the leds color arrays
        * Grab the screen
        * Resize the image to the resolution of the LEDs available (See note)
        * figure out which LED should have which HEX GRB color and update
          self.leds

        Note:
        Picking a pixel as a representation of which HEX RGB color each LED
        should have is naïve and will not render a true result. To get the
        desired color for each LED, we will have to interpolate a bunch of
        pixels' colors. The idea behind rezising the image is that instead of
        calculating zones for each LED and interpolating these zones to get
        the HEX RGB color that each LED should have, we resize the screen image
        to have as many pixels vertically and horizontally as we know we have
        LEDs and allow PIL to do the interpolation only once. Each pixel of
        the resized image will be an interpolated color that will result in
        each LED getting the right HEX RGB color.
        """
        self.leds = {side: [] for side in ["top", "right", "bottom", "left"]}
        screen = ImageGrab.grab()
        screen = screen.resize((H_LEDS, V_LEDS))
        if self.loglevel == "debug":
            screen.save(os.path.join("tmp", "screen.jpg"))

        for side in self.leds.keys():
            for coordinate in self.led_positions[side]:
                rgb = screen.getpixel(coordinate)
                self.leds[side].append(rgb)
            self.leds[side].reverse()
开发者ID:n1ck3,项目名称:ambiled,代码行数:31,代码来源:ambiled.py


示例16: _update_images

    def _update_images(self, delay):
        time.sleep(delay)
        files = {}

        if not self.screenshot_file:
            # take a screenshot with pyscreenshot
            im = ImageGrab.grab(bbox=(0, 0, self._screen_width, self._screen_height), backend='imagemagick')
        else:
            try:
                # used if screenshot already exists
                im = Image.open(self.screenshot_file)
            except IOError as e:
                logger.warn("Unable to open screenshot file {0}".format(self.screenshot_file))
                return
        output = cStringIO.StringIO()
        image_format = 'JPEG'
        if not self.high_quality:
            im.thumbnail((640, 360), Image.ANTIALIAS)
        else:
            image_format = 'PNG'

        if im.mode != "RGB":
            im = im.convert("RGB")
        im.save(output, format=image_format) # to reduce jpeg size use param: optimize=True
        files['galicaster'] = ('galicaster.jpg', output.getvalue(),
                               'image/jpeg')
        try:
            # add verify=False for testing self signed certs
            requests.post(
                "%s/image/%s" %
                (self._http_host, self.id), files=files, auth=(
                    self._user, self._password)) # to ignore ssl verification, use param: verify=False
        except Exception:
            logger.warn('Unable to post images')
开发者ID:SussexLearningSystems,项目名称:peakaboo,代码行数:34,代码来源:ddp.py


示例17: __init__

 def __init__(self, game_driver, source='ps', shift=[0,0]):
     if source == 'ps':#{{{
         self.im = pyscreenshot.grab()
     self.shift = shift 
     self.source = source
     self.game_driver = game_driver
     self.got_names = 'to start'#}}}
开发者ID:powerresearch,项目名称:Poker-Bot-Reformed,代码行数:7,代码来源:screen_scraper.py


示例18: start_scan

 def start_scan(self):
     # print(self.cursor, self.color)
     print('starting scan in 2')
     time.sleep(2)
     prev_position = [0, 0]
     while True:
         pyautogui.press('3')
         # time.sleep(1)
         color = self.color
         image = img.grab()
         for x in range(250, 1500, 2):             # change to fishing area
             for y in range(200, 650, 2):
                 color_now = image.getpixel((x, y))
                 if np.allclose(list(color_now), list(color), atol=10):
                     print('found color in position', x, y)
                     '''self.update_s2(color_now)
                     self.color_now = color_now
                     time.sleep(1)
                     win32api.SetCursorPos((x, y))
                     print('match!')
                     self.after(2000)'''
                     if abs(x - prev_position[0] >= 10) and abs(y - prev_position[2] >= 10):
                         prev_position[0] = x
                         prev_position[1] = y
                         win32api.SetCursorPos((x, y))
                         return self.wait_thread()
         print('scan Finished with no match...')
开发者ID:ucshadow,项目名称:Fish_bot,代码行数:27,代码来源:even+more.py


示例19: shoot

def shoot(x1,y1,x2,y2, *args, **kwargs):
    """Takes screenshot at given coordinates as PIL image format, the converts to cv2 grayscale image format and returns it"""
    # PIL format as RGB
    im = pyscreenshot.grab(bbox=(x1,y1,x2,y2)) #X1,Y1,X2,Y2
    #im.save('screenshot.png')

    # Converts to an array used for OpenCV
    im = np.array(im)
    # Next line needs to be taken out, messes up the array order when 
    # looking for hsv values
    #cv_img = im.astype(np.uint8)
    # Converts to BGR format for OpenCV
    cv_img = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)
    #cv2.imwrite('screenshot.png', cv_img)
    #cv2.imshow('screenshot', cv_img)
    #cv2.waitKey(0)
    #cv2.killAll()
    #return 

    try:
        if args[0] == 'hsv':
            #print('sending hsv')
            # returns hsv image
            hsv = cv2.cvtColor(cv_img, cv2.COLOR_BGR2HSV)
            return  hsv
            
    except:
        return cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
开发者ID:jjvilm,项目名称:elmacro,代码行数:28,代码来源:read-stats.py


示例20: getRgbOnScreen

 def getRgbOnScreen( self, x, y ):
     # must convert to RGB after grab,
     # because the format of grab is decide by internal algorithm
     # sometimes mode RGB, sometimes mode P (palette)
     im = ImageGrab.grab(bbox=(x, y, x + 1, y + 1)).convert('RGB')
     pix = im.getpixel((0,0))
     return pix
开发者ID:arton0306,项目名称:TetrisAi,代码行数:7,代码来源:BlockFetcher.py



注:本文中的pyscreenshot.grab函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python scsi.SCSI类代码示例发布时间:2022-05-27
下一篇:
Python pyscipopt.Model类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap