使用终端在python中查找图像像素?

时间:2012-09-26 07:04:29

标签: python macos terminal

考虑我在image.png文件夹中有一张图片XYZ。我需要一个Python脚本,要求用户输入图像名称,输出应该是图像的像素和大小。

我使用sips命令在终端上尝试如下:

sips -g pixelWidth -g pixelHeight image.png

我需要在Python上加入相同的内容。我尝试使用此代码

import os
for rootpath,dir,file in os.walk("/Volumes/Macintosh HD/users/username/myfolder"):
    for files in file:      
        def test(name):
            return (os.system(sips -g pixelWidth -g pixelHeight name))

但这没有用。我是Python新手并做了一些实验。所以任何帮助/想法将不胜感激:)

1 个答案:

答案 0 :(得分:1)

你的逻辑应该是:

  1. 检查图像文件是否存在,如果不存在,请退出相应的消息。
  2. 使用图片的完整路径
  3. 调用您的函数
  4. 将结果显示给用户。
  5. 以下是如何做到这一点:

    import os
    from subprocess import Popen, PIPE
    
    def run_command(user_input):
        image_path = '/home/user/images/'
        command_to_run = '/usr/bin/sips'
    
        if not user_input:
            return "You didn't enter anything!"
    
        if not os.path.exists(image_page+user_input):
            return "I cannot find that image!"
        else:
            output = Popen([command_to_run,
                            "-g", "PixelWidth",
                            "-g", "PixelHeight",
                            image_path+user_input], stdout=PIPE).communicate()[0]
            return "The result is: ",output
    
     user_input = raw_input("Please enter the image name: ")
     print run_command(user_input)