Skip to content

Commit

Permalink
Improving output (#15)
Browse files Browse the repository at this point in the history
* Modularity Update

* Turned output to logging

* autopep8

* Cleaned up output file path

* fixed output warning, other small fixes

* Logging updates

* README update
  • Loading branch information
BernardZhao committed Aug 23, 2019
1 parent 70d6d47 commit 953a38c
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 40 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Have a look at [this post](http://satyarth.me/articles/pixel-sorting/) or [/r/pi

### Dependencies

Tested with python3. Should work with python2 as well.
Python 3.6 or greater.

Requires Pillow. `pip install Pillow` should work. If not, see [here](https://pillow.readthedocs.org/en/3.0.0/installation.html#linux-installation) for details.

Expand Down Expand Up @@ -43,6 +43,7 @@ Angle | `-a` | Angle at which you're pixel sorting in degrees. `0` (horizont
External int file | `-f` | Image used to define intervals. Must be black and white.
Sorting function | `-s` | Sorting function to use for sorting the pixels.
Mask | `-m` | Image used for masking parts of the image.
Logging Level | `-l` | Level of logging statements made visible. Choices include `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`.

#### Interval Functions

Expand Down
33 changes: 23 additions & 10 deletions argparams.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import util
import interval
import sorting
import logging


def read_interval_function(int_function):
Expand All @@ -16,8 +17,8 @@ def read_interval_function(int_function):
"none": interval.none
}[int_function]
except KeyError:
print(
"[WARNING] Invalid interval function specified, defaulting to 'threshold'.")
logging.warning(
"Invalid interval function specified, defaulting to 'threshold'.")
return interval.threshold


Expand All @@ -31,7 +32,8 @@ def read_sorting_function(sorting_function):
"saturation": sorting.saturation
}[sorting_function]
except KeyError:
print("[WARNING] Invalid sorting function specified, defaulting to 'lightness'.")
logging.warning(
"Invalid sorting function specified, defaulting to 'lightness'.")
return sorting.lightness


Expand All @@ -58,8 +60,14 @@ def parse_args():
help="lightness, intensity, hue, saturation, minimum", default="lightness")
p.add_argument("-m", "--mask",
help="Image used for masking parts of the image")
p.add_argument("-l", "--log_level", default="WARNING", help="Print more or less info",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"])

__args = p.parse_args()

logging.basicConfig(
format="%(name)s: %(levelname)s - %(message)s", level=logging.getLevelName(__args.log_level))

return {
"image_input_path": __args.image,
"output_image_path": __args.output,
Expand All @@ -76,16 +84,21 @@ def parse_args():


def verify_args(args):

print("Interval function: ", args["interval_function"])
# Informational logs
logging.info(f"Interval function: {args['interval_function']}")
if args["interval_function"] in ["threshold", "edges", "file-edges"]:
print("Lower threshold: ", args["bottom_threshold"])
logging.info(f"Lower threshold: {args['bottom_threshold']}")
if args["interval_function"] == "threshold":
print("Upper threshold: ", args["upper_threshold"])
logging.info(f"Upper threshold: {args['upper_threshold']}")
if args["interval_function"] in ["random", "waves"]:
print("Characteristic length: ", args["clength"])
print("Randomness: ", args["randomness"], "%")

logging.info(f"Characteristic length: {args['clength']}")
logging.info(f"Randomness: {args['randomness']}%")
# Actual validation
if not args["output_image_path"]:
output = f"{util.id_generator()}.png"
logging.warning(
f"No output path provided, defaulting to {output}")
args["output_image_path"] = output
args["interval_function"] = read_interval_function(
args["interval_function"])
args["sorting_function"] = read_sorting_function(args["sorting_function"])
29 changes: 14 additions & 15 deletions interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
import random as rand
import constants
import util

# Interval functions
import logging

def edge(pixels, args):
img = Image.open(args["image_input_path"])
Expand All @@ -20,13 +19,13 @@ def edge(pixels, args):
edge_pixels = []
intervals = []

print("Defining edges...")
logging.debug("Defining edges...")
for y in range(img.size[1]):
filter_pixels.append([])
for x in range(img.size[0]):
filter_pixels[y].append(edge_data[x, y])

print("Thresholding...")
logging.debug("Thresholding...")
for y in range(len(pixels)):
edge_pixels.append([])
for x in range(len(pixels[y])):
Expand All @@ -35,13 +34,13 @@ def edge(pixels, args):
else:
edge_pixels[y].append(constants.black_pixel)

print("Cleaning up edges...")
logging.debug("Cleaning up edges...")
for y in range(len(pixels) - 1, 1, -1):
for x in range(len(pixels[y]) - 1, 1, -1):
if edge_pixels[y][x] == constants.black_pixel and edge_pixels[y][x - 1] == constants.black_pixel:
edge_pixels[y][x] = constants.white_pixel

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
for x in range(len(pixels[y])):
Expand All @@ -54,7 +53,7 @@ def edge(pixels, args):
def threshold(pixels, args):
intervals = []

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
for x in range(len(pixels[y])):
Expand All @@ -67,7 +66,7 @@ def threshold(pixels, args):
def random(pixels, args):
intervals = []

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
x = 0
Expand All @@ -85,7 +84,7 @@ def random(pixels, args):
def waves(pixels, args):
intervals = []

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
x = 0
Expand All @@ -111,13 +110,13 @@ def file_mask(pixels, args):
for x in range(img.size[0]):
file_pixels[y].append(data[x, y])

print("Cleaning up edges...")
logging.debug("Cleaning up edges...")
for y in range(len(pixels) - 1, 1, -1):
for x in range(len(pixels[y]) - 1, 1, -1):
if file_pixels[y][x] == constants.black_pixel and file_pixels[y][x - 1] == constants.black_pixel:
file_pixels[y][x] = constants.white_pixel

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
for x in range(len(pixels[y])):
Expand All @@ -138,13 +137,13 @@ def file_edges(pixels, args):
edge_pixels = []
intervals = []

print("Defining edges...")
logging.debug("Defining edges...")
for y in range(img.size[1]):
filter_pixels.append([])
for x in range(img.size[0]):
filter_pixels[y].append(edge_data[x, y])

print("Thresholding...")
logging.debug("Thresholding...")
for y in range(len(pixels)):
edge_pixels.append([])
for x in range(len(pixels[y])):
Expand All @@ -153,13 +152,13 @@ def file_edges(pixels, args):
else:
edge_pixels[y].append(constants.black_pixel)

print("Cleaning up edges...")
logging.debug("Cleaning up edges...")
for y in range(len(pixels) - 1, 1, -1):
for x in range(len(pixels[y]) - 1, 1, -1):
if edge_pixels[y][x] == constants.black_pixel and edge_pixels[y][x - 1] == constants.black_pixel:
edge_pixels[y][x] = constants.white_pixel

print("Defining intervals...")
logging.debug("Defining intervals...")
for y in range(len(pixels)):
intervals.append([])
for x in range(len(pixels[y])):
Expand Down
27 changes: 13 additions & 14 deletions pixelsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,53 +6,52 @@
from argparams import parse_args, verify_args
import util
import constants
import logging


def main(args):
verify_args(args)

print("Opening image...")
logging.debug("Opening image...")
input_img = Image.open(args["image_input_path"])

print("Converting to RGBA...")
logging.debug("Converting to RGBA...")
input_img.convert('RGBA')

print("Rotating image...")
logging.debug("Rotating image...")
input_img = input_img.rotate(args["angle"], expand=True)

print("Getting data...")
logging.debug("Getting data...")
data = input_img.load()

print("Loading mask...")
logging.debug("Loading mask...")
mask = Image.open(args["mask"]).convert(
'RGBA').load() if args["mask"] else None

print("Getting pixels...")
logging.debug("Getting pixels...")
pixels = get_pixels(data, mask, input_img.size)

print("Determining intervals...")
logging.debug("Determining intervals...")
intervals = args["interval_function"](pixels, args)

print("Sorting pixels...")
logging.debug("Sorting pixels...")
sorted_pixels = sort_image(
pixels, intervals, args["randomness"], args["sorting_function"])

print("Placing pixels in output image...")
logging.debug("Placing pixels in output image...")
output_img = place_pixels(sorted_pixels, mask, data, input_img.size)

if args["angle"] is not 0:
print("Rotating output image back to original orientation...")
logging.debug("Rotating output image back to original orientation...")
output_img = output_img.rotate(-args["angle"], expand=True)

print("Crop image to apropriate size...")
logging.debug("Crop image to apropriate size...")
output_img = util.crop_to(
output_img, Image.open(args["image_input_path"]))

print("Saving image...")
logging.debug("Saving image...")
output_img.save(args["output_image_path"])

print("Done!", args["output_image_path"])


def get_pixels(data, mask, size):
pixels = []
Expand Down

0 comments on commit 953a38c

Please sign in to comment.