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"""
# creates widht & height for screenshot region
w = x2 - x1
h = y2 - y1
# PIL format as RGB
img = pyautogui.screenshot(region=(x1,y1,w,h)) #X1,Y1,X2,Y2
#im.save('screenshot.png')
# Converts to an array used for OpenCV
img = np.array(img)
try:
for arg in args:
if arg == 'hsv':
# Converts to BGR format for OpenCV
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
return hsv_img
if arg == 'rgb':
rgb_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
return rgb_img
except:
pass
cv_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return cv_gray
python类screenshot()的实例源码
def image_is_on_screen(template_name):
template = cv2.imread(os.path.join(
'screenshots',
template_name + '.png'),
cv2.IMREAD_GRAYSCALE)
image = cv2.cvtColor(
np.array(pyautogui.screenshot(
region=(0, 0, 1300, 750))),
cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(res >= CLOSENESS_THRESHOLD)
# Not sure why this works but okay
for pt in zip(*loc[::-1]):
return True
return False
def set_image_of_slot(self):
self.image_of_slot = numpy.array(pyautogui.screenshot(region=(self.top_left_corner[0], self.top_left_corner[1] + 90, 165, 10)))
self.set_time_of_last_screenshot()
print('Image of {} has been updated'.format(self.item.item_name))
def screengrab_as_numpy_array(location):
im = numpy.array(pyautogui.screenshot(region=(location[0], location[1], location[2]-location[0], location[3] - location[1])))
return(im)
def check_if_image_exists(item_name):
global client_version
file_name = 'Tools/screenshots/items/' + client_version + '_items/' + item_name.replace(' ', '_') + '.png'
if os.path.isfile(file_name):
return(file_name)
else:
print('You do not have an image file for {} so the script is aborting, to fix this issue either take a screenshot of {} or remove it from the list of items to merch'.format(item_name, item_name))
def main():
box_1_coords = (43, 442, 159, 42)
box_2_coords = (215, 442, 159, 42)
box_3_coords = (387, 442, 159, 42)
box_4_coords = (43, 498, 159, 42)
box_5_coords = (215, 498, 159, 42)
box_6_coords = (387, 498, 159, 42)
time.sleep(3)
list_of_items = ['Incandescent energy', 'Coal', 'Fire rune', 'Air rune', 'Feather', 'Broad arrowheads', 'Maple logs', 'Water rune', 'Earth rune', 'Nature rune',
'Yew logs', 'Brilliant energy', 'Blood rune', 'Mind rune', 'Cannonball', 'Lustrous energy', 'Luminous energy', 'Dragon bones', 'Body rune', 'Mahogany plank',
'Death rune', 'Royal bolts', 'Ascension bolts', 'Fishing bait', 'Rune arrow', 'Chaos rune', 'Bowstring', 'Ascension shard', 'Radiant energy',
'Ganodermic flake', 'Adamantite ore', 'Gold ore', 'Flax', 'Vial of water', 'Vibrant energy', 'Araxyte arrow', 'Mahogany logs', 'Raw shark', 'Shark', 'Soul rune',
'Rocktail', 'Adamant bar', 'Rune bar', 'Gold bar', 'Elder energy', 'Runite ore', 'Law rune', 'Raw lobster', 'Raw rocktail', 'Astral rune', 'Cosmic rune',
'Black dragon leather', 'Onyx bolts (e)', 'Steel bar', 'Magic shieldbow', 'Iron ore', 'Black dragonhide', 'Grenwall spikes', 'Mithril bar', 'Willow logs', 'Mud rune',
'Lobster', 'Swamp tar', 'Mithril ore', 'Adamant arrow', 'Snape grass', 'Soft clay', 'Magic notepaper', 'Steel arrow', 'Magic shieldbow (u)', 'Harralander tar',
'Mithril arrow', 'Teak plank', 'Thread', 'Oak plank', 'Dark arrow', 'Grimy dwarf weed', 'Dragon arrowheads', 'Grimy lantadyme', 'Airut bones', 'Gleaming energy',
'Infernal ashes', 'Frost dragon bones', 'Living minerals', 'Chitin scraps', 'Green dragon leather', 'Red chinchompa', 'Rune arrowheads', 'Clean lantadyme', 'Rune essence', 'Raw tuna',
'Hydrix bolt tips', 'Yew seed', 'Palm tree seed', 'Teleport to house', 'Wine of Zamorak', 'Potion flask', 'Prayer potion (4)', 'Super restore (4)', 'Saradomin brew (4)',
'Aggression potion (4)', 'Prayer renewal (4)']
list_of_file_names = []
for i in range(len(list_of_items)):
list_of_file_names.append(list_of_items[i].replace(' ', '_')+'.png')
for i in range(len(list_of_items)):
file_name_1 = 'screenshots/items/nxt_items/'+list_of_file_names[i]
file_name_2 = 'screenshots/temp_items/'+list_of_file_names[i]
if os.path.isfile(file_name_1):
print('file exists', file_name_1)
continue
x = len(list_of_items[i])
pyautogui.typewrite(list_of_items[i], random.random()/10)
time.sleep(4)
pyautogui.screenshot(file_name_2, region=(box_2_coords))
for x in range(x):
pyautogui.press('backspace')
time.sleep(random.random()/10)
time.sleep(1)
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')
def spec_printscreen():
# identify the top-right corner, doesnt find it!!
# ===========================================================================
# region_topright = pyautogui.locateOnScreen('topright.png')#,grayscale=True)
# if region_topright is None:
# print('Could not find topright picture')
# else:
# print(region_topright)
# ===========================================================================
# identify thedownleft corner from home button
region_downleft = pyautogui.locateOnScreen('downleft.png')
if region_downleft is None:
print('Could not find downleft picture')
else:
# print(region_downleft)
pass
fig = plt.gcf()
size = fig.get_size_inches() * fig.dpi # size in pixels
# print(size)
# im=pyautogui.screenshot(region=(0,0, 300, 400))
pyautogui.screenshot()
im2 = pyautogui.screenshot('latest_screenshot.png',
region=(region_downleft[0], region_downleft[1] - size[1], size[0], size[1]))
ctypes.windll.user32.MessageBoxA(0, "spec print screenshot finished, find it in latest_screenshot.png",
"Screenshot of the plot area", 0)
def detect_position(self):
screen = ag.screenshot()
for name, offset_x, offset_y in [('start', 288, 252), ('select_title', 28, 24)]:
position = self.find_image(screen, self.images[name])
if position != None:
x, y = position
x -= offset_x
y -= offset_y
self.set_position(x, y)
return (x, y)
return None
def screenshot(x):
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y_%m_%d %H_%M_%S')
gui.screenshot("screenshot/" + st + ".png")
def take_screenshot():
file_name = 'screenshots/' + input("What would you like to save the screenshot as? Please enter the entire file name including extension, ie .png\n")
input("Place curser over the top left corner of the box you'd like to screenshot and press enter")
top_left = pyautogui.position()
input("Place curser over the bottom right corner of the box you'd like to screenshot and press enter")
bottom_right = pyautogui.position()
time.sleep(3)
width = bottom_right[0] - top_left[0]
height = bottom_right[1] - top_left[1]
pyautogui.screenshot(file_name, region=(top_left[0], top_left[1], width, height))