From: Robin Krens Date: Sat, 27 Jan 2024 19:49:11 +0000 (+0100) Subject: haptic-extractor.py: cleaner 2 subplots X-Git-Url: https://robinkrens.nl/gitweb/?a=commitdiff_plain;h=e6e562dbabaaef84f023debdd74389a856907428;p=haptic-extractor haptic-extractor.py: cleaner 2 subplots --- diff --git a/haptic-extractor.py b/haptic-extractor.py index a45ea36..bd1a57e 100644 --- a/haptic-extractor.py +++ b/haptic-extractor.py @@ -1,17 +1,19 @@ +# /usr/bin/python3 # -# haptic-extractor.py [option] input_image output +# Usage: +# haptic-extractor.py [option] input_image output_image # # Options -# -v Generate a vertical profile through the image. -# -s generate a 150x100 thummbnail image (default 300x200 pixels) -# -g Draw the profile in green instead of red -# -b Draw the profile in blue instead of red +# --transpose Generate a vertical profile through the image +# --color=COLOR Draw the graph in a different color # #### + from PIL import Image import matplotlib.pyplot as plt import numpy as np import signal +import wave import sys import os @@ -22,7 +24,7 @@ def usage(message): """Output the script comments as docs""" print(f"{PROGNAME}: {' '.join(sys.argv[1:])}") with open(os.path.join(PROGDIR, PROGNAME), 'r') as script_file: - lines = script_file.readlines()[2:] + lines = script_file.readlines()[1:] for line in lines: if line.startswith('###'): break @@ -37,20 +39,17 @@ def error(message): sys.exit(1) COLOR = 'red' -VERTICAL = SMALLER = False +TRANSPOSE = False +DEBUG = False args = iter(sys.argv[1:]) for arg in args: if arg in ('--help', '-h'): usage() - elif arg == '-v': - VERTICAL = True - elif arg == '-s': - SMALLER = True - elif arg == '-g': - COLOR = 'green' - elif arg == '-b': - COLOR = 'blue' + elif arg in ('--transpose', '-t'): + TRANSPOSE = True + elif arg in ('--verbose'): + DEBUG = True elif arg in ('-', '--'): break elif arg.startswith('-'): @@ -61,13 +60,9 @@ for arg in args: if len(sys.argv) == 1: usage("Missing input_image") -# Check for too many arguments if len(sys.argv) > 3: usage("Too many arguments") -# Temporary working images with auto-clean-up on exit -input_image = f"/tmp/im_profile_{os.getpid()}.miff" - def cleanup_handler(signum, frame): """Cleanup function to be executed on exit""" os.remove(input_image) @@ -79,12 +74,16 @@ def cleanup_handler(signum, frame): try: input_image_path = sys.argv[1] - output_image_path = "./im_profile_strip.png" + if len(sys.argv) == 3: + output_image_path = sys.argv[2] + else: + base_name, ext = os.path.splitext(os.path.basename(input_image_path)) + output_image_path = f"{base_name}_output{ext}" image = Image.open(input_image_path) # Apply the specified vertical transformation - if VERTICAL: + if TRANSPOSE: image = image.transpose(Image.Transpose.ROTATE_90) # Crop the image to a 1xwidth size at the center of the height @@ -95,19 +94,16 @@ try: image = image.crop((0, top, width, bottom)) # Save the result - image.save(output_image_path, format="PNG") + #image.save(output_image_path, format="PNG") except Exception as e: print(f"Error: {e}") + usage(e) sys.exit(1) -image = Image.open("./im_profile_strip.png") +#image = Image.open("./im_profile_strip.png") image = image.convert('L') -# Resize the image to a 1xN size -#gsize_w = 300 # Replace with your desired gsize_w -#image = image.resize((300, 1), resample=Image.BICUBIC) - # Convert the image to a NumPy array image_array = np.array(image) image_flat = image_array.flatten() @@ -116,50 +112,31 @@ image_flat = image_array.flatten() bit_depth = image_array.dtype.itemsize * 8 # Print the values in a format similar to the original script -for value in image_array.flatten(): - print(value, end=' ') - -print(f"\nBit Depth: {bit_depth} bits") - -# plt.plot(image_flat, linestyle='-', linewidth=2, color='blue') +if DEBUG: + for value in image_array.flatten(): + print(value, end=' ') -gsize_w = 100 + print(f"\nBit Depth: {bit_depth} bits") -#fig, ax = plt.subplots(figsize=(4, 2.25)) # Adjust the figure size as needed fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(3, 3), gridspec_kw={'height_ratios': [3, 1]}) - -# Plot the grayscale line plot -ax1.plot(image_flat, linestyle='-', linewidth=2, color='gray') +ax1.plot(image_flat, linestyle='-', linewidth=1, color='gray') # Customize x and y ticks ax1.set_xticks([]) -ax1.set_ylim(0, 255) # Set y-axis range from 0 to 255 -ax1.set_yticks([0, 128, 255]) # Adjust y-axis ticks as needed +ax1.set_ylim(0, 255) +ax1.set_yticks([75, 150, 225]) ax1.set_xticklabels([]) ax1.set_yticklabels([]) -# Plot the image on the second subplot (ax2) +# resize picture a bit and attach at bottom +width, height = image.size +image = image.resize((width, 5), resample=Image.BICUBIC) ax2.imshow(image, cmap="gray") ax2.axis('off') # Hide axis for the image subplot plt.subplots_adjust(hspace=0) -fig.tight_layout(rect=[0, 0, 1, 0.95]) - -# Add the original image at the bottom -#axins = ax.inset_axes([0, -0.3, 1, 0.3]) -#axins.imshow(image, cmap='gray') - -# Remove x and y tick labels from the inset_axes -#axins.set_xticks([]) -#axins.set_yticks([]) - -#fig.subplots_adjust(bottom=0, top=1, hspace=0) - -#bottom_image_ax = fig.add_axes([0.05, 0.0, 1, 0.01]) -#bottom_image_ax.imshow(image, cmap='gray') -#bottom_image_ax.axis('off') - -plt.savefig('output_plot.png', dpi=300, bbox_inches='tight') +fig.tight_layout(pad=0) +fig.tight_layout(rect=[0, 0, 1, 0.90]) -# Show the plot -# plt.show() +print(f"Written output file {output_image_path}") +plt.savefig(output_image_path, dpi=100, bbox_inches='tight')