如何使用python从屏幕的给定区域拍摄快照? [英] How to take snapshot from given region of the screen with python?

查看:85
本文介绍了如何使用python从屏幕的给定区域拍摄快照?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的想法:1) 从屏幕上对给定区域进行快照,如 (100,100,80,60),将结果保存为图像2)使用OpenCV python界面处理图像

Here is my thoughts: 1) snap shot the given region from the screen like (100,100,80,60), save the result as image 2) process the image with OpenCV python interface

只是第一个使用python的人,想知道这是否是一个很好的解决方案,想知道如何使用python进行快照.

Just be first to python and wonder if this is good solution,be specific,wonder how to snapshot with python.

谢谢

推荐答案

在Apple的 CoreGraphics api中使用 CGRectMake 相当简单:

It's fairly simple using CGRectMake in Apple's CoreGraphics api:

CG.CGRectMake(x, y, w, h)

这使您可以分别定义水平/垂直位置和宽度/高度.

This allows you to define the horizontal/vertical positions, and width/height respectively.

代码:

#!/usr/bin/python

import Quartz
import LaunchServices
from Cocoa import NSURL
import Quartz.CoreGraphics as CG

def screenshot(path, dpi, region = None):

    if region is None:
        region = CG.CGRectInfinite

    image = CG.CGWindowListCreateImage(
        region,
        CG.kCGWindowListOptionOnScreenOnly,
        CG.kCGNullWindowID,
        CG.kCGWindowImageDefault)

    url = NSURL.fileURLWithPath_(path)

    dest = Quartz.CGImageDestinationCreateWithURL(
        url,
        LaunchServices.kUTTypePNG, 1, None
        )
    prop = {
        Quartz.kCGImagePropertyDPIWidth: dpi,
        Quartz.kCGImagePropertyDPIHeight: dpi,
        }

    Quartz.CGImageDestinationAddImage(dest, image, prop)
    Quartz.CGImageDestinationFinalize(dest)

spec = (0, 0, 800, 600) # x, y, w, h
path = '/path/to/screnshot_region.png' # save path
area = CG.CGRectMake(*spec) # set area to cgrect

screenshot(path, dpi=72, region=area) # call function

要使用,只需调用函数:

To use, just call the function:

screenshot(path, dpi=72, region=area)

* dpi 将设置图像输出分辨率;省略 region 参数进行全屏捕获.关于 OpenCV 部分-目前我使用它的频率不足以提供任何功能.

*dpi will set the image output resolution; leave out the region argument for fullscreen capture. In regards to the OpenCV portion - I don't use it often enough to provide anything at this time.

这篇关于如何使用python从屏幕的给定区域拍摄快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆