AHK: How to Loop Code through Images

Need to make changes to every pixel in an image? As it turns out, that’s not so difficult with AutoHotkey. From what I’ve been able to gather, all you really need is the height and width of the picture so that the loop knows how many times to run and the XY coordinates of the picture’s upper left corner.

The Code

Note that CoordMode, Pixel, Screen tells the computer to use the XY coordinates relative to the screen rather than the window.

CoordMode, Pixel, Screen

Height:=Height of the Image
Width:=Width of the Image
Xaxis:=X-Coordinate to start at
Yaxis:=Y-Coordinate to start at

loop, %Height%
{
loop, %Width%
{

Do This Code, Xaxis, Yaxis

Xaxis++

}
Xaxis:= Xaxis-Width
Yaxis++
}

How the Loops Work

LoopsExplained

So basically, it’s an X-axis loop within a Y-axis loop. Take the blown-up image above. It’s an extremely simplified example, using a 4X4 square.

Note that before starting the loop, X and Y axis starting coordinates will need to be set. In this case, both are 1. Variables for the height and width will also need to be set. In this case, both are 4.

Once both loops begin, the XY will start at (1,1) . The inner loop will run whatever code is specified, and x++ will add 1 to the X-axis. It’ll loop this through however many pixels are set for the image width. For the above, it’ll stop when it hits (4,1), then proceed to the outer loop.

The code at the end of the outer loop has to reset the X-axis, otherwise the inner loop will just keep adding to it. That’s why we start off with Xaxis:= Xaxis-Width. Then y++ adds 1 to the Y-axis to take the code down a row, and the inner loop runs again.

This will keep going until the Y-Axis hits the specified height. In the end, that means the computer will have run the code on 16 pixels total. Unfortunately, most images will be larger than this one, so don’t be surprised if it takes a while to go through each pixel.

 

 

Advertisements
Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: