r/dailyprogrammer • u/Cosmologicon 2 3 • May 03 '17
[2017-05-03] Challenge #313 [Intermediate] PGM image manipulation
Description
Write a program that can perform the following operations on a given plain PGM image (described below):
- R: rotate 90 degrees right (clockwise)
- L: rotate 90 degrees left (counterclockwise)
- H: flip horizontal
- V: flip vertical
It must also handle combinations of these, applied in order from left to right. For instance, HL means flip horizontal, and then rotate left. Note HL is different from LH, which is rotate left and then flip horizontal. The set of operations to perform will be given when your program is run.
Example input
Example outputs
Input/output specification
Because plain PGM images are plain text, my recommended way of handling this is to read the input image from standard in, write the result to standard out, and use command-line arguments to specify what operations you want done. My solution is run from the command line like this:
python pgm-manip.py HRVRLLHL < input.pgm > output.pgmHowever, you're not required to do it this way.
Plain PGM image specification
The plain PGM format is a text-based grayscale image format that works in most image viewers, so you can open the file you output to check your work. Here's an example:
P2 4 3 100
0
100
100
0
100
33
33
100
0
100
100
0The first line contains four things: the string P2, the image width in pixels (4 in this case), the image height (3 in this case), and the maximum pixel value (100 in this case). Each of the remaining lines (4x3, or 12 in this case) contains the value of a single pixel, where 0 is black and 100 is white, in order starting at the top left.
As the link says, the PGM format allows any layout of these values, as long as there's whitespace between them. However, you may assume that the values are laid out as above. Also the PGM format allows comments with #, but you may assume there are no comments.
Previous r/dailyprogrammer challenges using related formats include Easy #172, Intermediate #172, and Easy #248. (Intermediate #171 was a related challenge with an ad-hoc image format.)
Your language may have a handy library for manipulating images. If you really feel like it, you can use that, I guess, but the spirit of the challenge is to manipulate the pixel values yourself.
Optional Bonus 1
Optimize your program so that it can efficiently handle many compound operations. I don't want to give away too much here, but for instance, the operation HRLVH is actually the same as simply V. So if you realize that, you don't need to apply each of the five operations separately. You can get away with one. In fact, there are only eight possible outputs from your program, no matter how many operations are requested.
If you do this right, then you should be able to run your program for thousands of operations, and it should only take slightly longer than if you run it for only one operation.
Optional bonus 2
Also handle the following operations:
- E: enlarge. Image size increased by 2x.
- S: shrink. Image size decreased by 2x.
- N: negative. All pixel values are replaced with their opposite (i.e. black and white are swapped)
- B: brighten. All pixel values are increased by some amount.
- D: darken. All pixel values are decreased by some amount.
- C: increase contrast. Pixel values become more spread out from 50%.
- W (washout): decrease contrast. Pixel values get moved closer to 50%.
Some of these operations are "lossy", meaning that if you apply them, it may not be possible to get back to your exact original image. But try to make it so that E/S, B/D, and C/W are roughly opposites. This means that BD should, roughly speaking, get you back to your original image, the same way RL, HH, or NN does.
Optional bonus 3
Also handle plain PPM images. These are similar to PGM's but they're in color, with three values for each pixel. Your same program should handle both PGM and PPM. You can tell which one it is because PGM's start with P2 and PPM's start with P3. Example input:
Ideally your program will handle both PGM and PPM in the same code path, with only small differences for the two formats, rather than two completely separate code paths.
5
u/den510 May 03 '17
Woke up to the notification of a new challenge and saw it was image manipulation. It's too early for that.
5
u/J_Gamer May 05 '17
C++ Bonus 1 and 2
Opted to not go lossless with the operations from bonus 2.
4
u/popillol May 03 '17 edited May 03 '17
Go / Golang Playground Link. No language shortcuts (doubt there even are any). Partly half-assed bonus 1. Set up to be able to add bonus 2 (which I might do later).
Code:
Output:
Method:
3
u/bss-applications May 03 '17
I've spent the afternoon on this one, pretty much since it was posted 5 hours ago. I now have a fully working version 1 with no bonuses. I'm going to hold off posting any code until I've got all 3 bonuses done.
So far, I have to say this is the best challenge I've tried here. Only being doing this for a couple of weeks, but I do like how it's been presented and how the three options ramp up and build on each other.
I've been able to see what I need to do and break it down to managable components pretty easily. I can already see how to do bonuses 1 and 3, and most of bonus 2.
Going to have a fun day tomorrow!
3
u/skeeto -9 8 May 03 '17 edited May 04 '17
C without bonus. The operation is "interpreted" for each pixel as it's written out.
2
u/Godspiral 3 3 May 03 '17
in J,
an enlarge algo, would just quadruple pixels... copy to left and right and diagonal down.
shrink would take even rows and cols.
2
u/zatoichi49 May 03 '17 edited May 05 '17
Method:
My approach was to try and solve this without using any libraries. Split the inputs into an array, then use list slicing and zip to build individual functions for flipping (h, v) , rotating (r, l), size changes (e, s) and value changes (n, b, d, c, w). Then add a final function that takes the transform codes in any order/combination and print as standard out.
Python 3: (with Bonus 1 and 2)
2
u/KeinBaum May 03 '17 edited May 03 '17
Scala, all boni
All operations are lossless until the final image is written, i.e. if you perform 500 darkens followed by 500 brightens, you will get back the original even if 500 darkens alone would result in an all black image.
Also the parsing and processing of the comand line arguments happens concurrently with the reading of image. That's probably a bit overkill because the image reading will take a lot longer than then command line arguments but I figured I might as well do it since it only takes a few extra lines of code.
2
u/[deleted] May 04 '17 edited May 04 '17
JavaScript
This isn't really a true response to the challenge, but I made a quick .pgm viewer in a codepen here. I was going to do the full challenge, but I ran out of free time.
2
u/[deleted] May 06 '17
Rust
Bonus 1. I convert the commands to matrices, multiply them, then convert back to the command.
2
u/SpasticSquid May 07 '17
Python3 with bonuses 1 and 2. Most interesting things are the contrast and washout transformations, they are exact inverse functions of each other, and neither is "lossy".
1
u/quantik64 May 03 '17 edited May 03 '17
PYTHON 3
NOW WITH SOME BONUS! (More to come shortly)
I'm confused how to do the ENLARGE and SHRINK though without losing any informations about the input PGM
1
u/Aeroway May 03 '17 edited May 04 '17
SCALA!
First the operations:
Images are defined by the 2D immutable array ("vector" in Scala) of their pixels. I probably should have created a separate Pixel object, but hey, I didn't do bonus 3 so whatever ;P
In the spirit of functional programming, Images are immutable and return a new Image object after an operation is performed.
Also defined a companion object to contruct Images from pgm files (or at least, the string itself. Didn't bother with IO.)
You can play around with it here!
1
u/[deleted] May 03 '17
In C, no bonus for now.
1
u/[deleted] May 04 '17
C, with some bonus exercises, and I added a 'G' option to turn the image grayscale. Before writing the image, the program detects whether the image is grayscale or not, and decides whether to output a P2 or P3 image based on that. Therefore a P3 image can be converted to a P2 image by the command
pnm-manip G < image.ppm.1
u/bss-applications May 04 '17 edited May 04 '17
I think I've overworked this one! 516 lines of C# code in Visual Studio later and everything complete through Option Bonus 2 now complete. Complete with error checking and help options. $crazy!
Thanks to u/popillol and his GO code for getting me started on Bonus 1! (why didn't I see that sooner?).
Later today I'll had in bonus 3, that shouldn't require too many changes to what I have so far....
1
u/LenAnderson May 04 '17 edited May 04 '17
Groovy with bonus 1 and 2
EDIT: can be called like OP's example:
groovy pgmManip.groovy HRVRLLHL < input.pgm > output.pgm1
u/bss-applications May 04 '17 edited May 04 '17
C#
OK, here goes nothing!...
All in complete. 608 lines of C# code answering all parts including all three bonuses...and...followed u/enloven's lead and added in a G function for Greyscale conversion of P3 colour files.
As ever, probably not the most efficient code. Love to hear ideas/thoughts of how I could tighten it up/improve it.
The general solution was a Class to hold the image specification and functions to manipulate. The image is stored in an array and manipulations are done using nested for...loops to copy values into new positions in a temporary array.
Because it so long, instead of code dumping here, I've hosted the final version of bitbucket:
https://bitbucket.org/snippets/BSS-Applications/n7Bre.
Below is the (still rather long) core pgmImage Class that does all the heavy lifting. Minor spoiler alerts inluded in the source below for anyone looking at Bonus 3 (or at least my way of handling Bonus 3):
1
u/[deleted] May 04 '17
C++, no bonuses yet. My first intermediate submission :)
1
u/[deleted] May 04 '17
Rust 1.17 No bonuses. Still new to Rust so took me a bit longer. That and it took me longer than I care to admit to figure out how to calculate the coordinates for the rotation transformations. Feedback welcome and encouraged as always :)
1
u/j3r3mias May 04 '17
Python 2.7 with bonus 1:
1
u/Scroph 0 0 May 04 '17
Experimenting with D's Mir library. Right now it's part of the std.experimental module of the standard library but it's probably going to be removed since it's already marked as deprecated in the DMD version I'm using. No bonus so far, except for a naive implementation of the first bonus that probably doesn't count :
1
u/qwesx May 04 '17
Another D solution. I put in Bonuses 1 and 3, it's getting late, so I'll probably implement bonus 2 tomorrow or on the weekend or something. I did image loading and transformation by hand, and I actually save PGMs as PPMs, except the same greyscale value for all three bytes.
If you wonder about the structure: I made myself a small testing framework to get a semi-automatic thing going. I'll spare you the ppgm_reader module as it's pretty boring: read file, create array of numbers and then move around the numbers when flipping or rotating the image. Though I found some inspiration in the other comments: I could just change the way an index is looked up instead of moving around the bytes. However, that would massively slow down comparing files (right now it's just a "are those two arrays identical?"-check). No idea what's faster, too lazy to actually implement it.
It takes on average about 140 ms for all 10 tests. I think that's pretty okay.
1
u/DrewBear21 May 04 '17 edited May 05 '17
Python 3
No bonus, but did use standard in and out with command line arguments. Might come back to it later and do some of the bonuses. Would really appreciate feedback on how to clean up or improve my code, I was confident in solving the problem but not solving it well (e.g. the loops for changing colors).
edit: added bonus 2 - C & W
1
u/SlenderOTL May 05 '17
Python 3 No bonuses, I didn't make it work from the command line as the question asked... But nonetheless, the rest works, I guess. This is my first answer on this sub, and any help on optimizing/cleaning up my code would be appreciated :)
1
u/goodygood23 May 05 '17 edited May 05 '17
R No bonuses yet. Might edit this later with some bonuses.
edit: This doesn't work. Have to think about the header more.
1
u/popeus May 05 '17
Python 3.6 No Bonus. I may return to attempt the bonus #2. Note: I used some slightly more exciting images found here. As such my header rows are a different format.
1
u/CountChokie May 06 '17
This is my first time coding something other than basic scripts for work - first time with NumPy and ArgParse. Any comments or questions would be appreciated.
Thank you.
In Python,
1
u/Executable_ May 09 '17
Python3 with bonus 1 :)
1
u/guatsf Jun 09 '17
R with bonus 1
Any comments and ways I can make this better are always much appreciated.