2

I have code which prints the latest file path of an image snapshot that is saved when motion is activated, I'm trying to use this file path as input to the next part of my code which converts the image to leave only the blue blobs. Any help is appreciated, I'm new to code.

#!/bin/bash/python

import os
from subprocess import  check_call

path = '/..'
os.chdir(path)
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)

newest = files[-1]
if newest == "Thumbs.db":
        'newest = files[-1]

newest = [path+"/"+newest]
a = newest

print newest
##### convert to blue blobs
check_call(["sudo","convert","imgIn.jpg", "-posterize","2","imgOut.jpg"])

check_call([ "sudo",'convert', 'imgIn.jpg', '-matte', '(', '+clone', '-fuzz',     57%', '-opaque', 'black', '-transparent', 'blue', ')', '-compose', 'DstOut', '-    composite', 'imgOut.jpg'])

How do I use the file path of newest as imgIn.jpg?

James Mills
  • 18,669
  • 3
  • 49
  • 62
Owen Lyons
  • 65
  • 9

1 Answers1

1

Writing a function called get_latest_file():

from os.path import isabs, getmtime
from os import getcwd, listdir, path


def get_latest_file(p):
    if not isabs(p):
        p = path.join(getcwd(), p)
    files = sorted([path.join(p, x) for x in listdir(p)], key=getmtime)
    return (files and files[-1]) or None

This will get you the latest file sorted by modified time and returning the last/newest matching file for a given directory.

Note: One thing to note here in the above function is that you need to build up a list of absolute paths for the sorting key getmtime() to work correctly or it will throw OSError(s) since os.listdir() gives you a list of "names" in a given directory as relative names.

Example:

get_latest_file("images")

Then you can pass the result of this to your check_output() call:

latest_image = get_latest_file("images")
check_call(["sudo", "convert", latest_image, "-posterize", "2", "imgOut.jpg"])

Update: You could then finish this off by writing one more function called convert_image() like this:

from os.path impomrt splitext
from subprocess import check_call


def convert_image(inf):
    base, ext = splitext(inf)
    outf = "{0:s}-converted{1:s}".format(base, ext)
    check_call(["sudo", "convert", inf, "-posterize", "2", outf])

Update #2: In terms of passing in the path for get_latest_file() you have probably three choices here:

IMAGE_PATH = "/path/to/images"                   # hard coded

image_path = raw_input("Enter path to image: ")  # prompt user

image_path = sys.argv[1]                         # from the command line

Side Note: Your Shebang is not quite right; it should read: #!/usr/bin/env python

References:

James Mills
  • 18,669
  • 3
  • 49
  • 62
  • Thanks, looks like I'm on the right track. Still having problems though, do I need to insert the path of the folder into that code? – Owen Lyons May 14 '15 at 03:54
  • Into the ``get_latest_file()`` function call? Yes. You *could* get the path from teh command-line via ``sys.argv[1]`` for example. – James Mills May 14 '15 at 03:56
  • Thanks, you're very helpful, I'm still quite confused about how to put this together in one working script. – Owen Lyons May 14 '15 at 04:17
  • Give it a try and post it to [Code Review](http://codereview.stackexchange.com/) if you get stuck or want someone to look over your attempt. – James Mills May 14 '15 at 04:18
  • @JamesMills Stack Overflow is the site that helps debug code, Code Review only improves working code. –  May 14 '15 at 04:21
  • 1
    @Hosch250 Wrong; There is a "Vote to Close" because "Question asking help with debugging". i.e: [stackoverflow](http://stackoverflow.com/) is **NOT** a debugging or trouble shooting service (*although admittedly a lot of us oblige!*) – James Mills May 14 '15 at 04:23
  • I keep getting this error? OSError: [Errno 2] No such file or directory: '/home/pi/images' – Owen Lyons May 14 '15 at 04:49
  • @OwenLyons We would need ot see the full traceback to understand the error more precisely; ``OSError: [Errno 2] No such file or directory: '...'`` means precisely what it means! Check the path you're using and the function you're calling. – James Mills May 14 '15 at 04:51
  • [1] Started stream webcam server in port 8081 [1] File of type 1 saved to: /home/pi/Desktop/DartProj/DartORG/20150514054817.jpg Traceback (most recent call last): File "/home/pi/Desktop/DartProj/fun.py", line 14, in get_latest_file("images") File "/home/pi/Desktop/DartProj/fun.py", line 11, in get_latest_file files = sorted([path.join(p, x) for x in listdir(p)], key=getmtime) OSError: [Errno 2] No such file or directory: '/home/pi/images' – Owen Lyons May 14 '15 at 04:56
  • ``line 14, in get_latest_file("images")`` <-- Did you really copy/paste the examples I wrote as-is without modification? – James Mills May 14 '15 at 04:58
  • Haha yep complete beginner, I replaced "images" with the folder path as I had asked earlier about, same result :) – Owen Lyons May 14 '15 at 05:02
  • Sorry @OwenLyons this is getting into the "discussion" etiquette of SO. *Please avoid extended discussions in comments* I recommend you ask a different more specific question :) – James Mills May 14 '15 at 05:05
  • @JamesMills I'm sorry, but as a regular at CR, questions containing broken code or asking for help implementing a new feature are closed immediately. –  May 14 '15 at 05:20
  • @Hosch250 Questions seeking to debug problematic code (*especially quite complex debugging problems*) are closed immediately here too :) – James Mills May 14 '15 at 05:24
  • OK, I just didn't want the OP to needlessly cross post. Thanks for the tip! –  May 14 '15 at 05:25
  • @Hosch250 No neither did i! I was hoping the OP had enough to write a mostly correct implemtnation! This discussion is getting out of hand :) – James Mills May 14 '15 at 05:26