<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def cmd_filter(args):
 """Filter an image. Parameters args : `argparse.Namespace` Command arguments. """

    check_output_format(args.output, args.count)

    img = Image.open(args.input)
    width, height = img.size

    if args.state is not None:
        markov = load(MarkovImage, args.state, args)
    else:
        args.state = ()
        if args.type == JSON:
            storage = JsonStorage(settings=args.settings)
        else:
            storage = SqliteStorage(settings=args.settings)
        markov = MarkovImage.from_storage(storage)
        read([args.input], markov, args.progress, False)

    args.level = min(args.level, markov.levels - 1) - 1

    if args.level < 0:
        args.level = -1
        scale = markov.scanner.min_size
        width, height = width // scale, height // scale
        start = None
    else:
        scale = reduce(
            lambda x, y: x * y,
            islice(markov.scanner.level_scale, args.level, markov.levels),
            1
        )
        width, height = width // scale, height // scale
        start = img.resize((width, height), markov.scanner.scale)

    for fname in outfiles(markov, args.output,
                          args.count, args.progress, args.level + 1):
        img = markov(
            width, height,
            state_size=args.state_size,
            start_level=args.level,
            start_image=start
        )
        save_image(img, fname)