ClickImageCenter() - Accurately Clicks Image Centroid (No External Libraries)

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
Tigerlily
Posts: 377
Joined: 04 Oct 2018, 22:31

ClickImageCenter() - Accurately Clicks Image Centroid (No External Libraries)

11 Oct 2018, 07:20

/*

I feel like many scripts are posted on here without enough context and it wastes peoples time as they look for a solution to their issues
and find nothing useful. This is why I'm going to go into detail about this very simple image center clicking script. I hope you really enjoy
it and find it useful to have at your disposal!

Code: Select all

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

–––––––––––––––––––––––––––––––––––––––––––		FIND & CLICK IMAGE CENTER		 ––––––––––––––––––––––––––––––––––––––––––

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

––––––––––––––––––––––––––––––––––––––––––––––	~	Coded by TƒGER LIL¥  ~	 ––––––––––––––––––––––––––––––––––––––––––––––

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



WHAT THIS SCRIPT DOES:

The purpose of this script is to find a specific image on your screen and then click in the center of that image. It was difficult to find an 
accurate and reliable way of doing this without downloading an external library and meddling with that, so I made my own simple solution.
I automate business and marketing tasks, so this was built to scale and use hundreds of times in one long progression of steps to obtain 
specific data and create enterprise-level reports. This is especially useful when there is no way to navigate around webpages you need to
extract data from without clicking buttons with the mouse (i.e. can't use keyboard or other methods to navigate).

BREAKDOWN:

- Entire screen of main monitor is scanned for an exact match of an image named "YourImageFileName.filetype"
- "YourImageFileName.filetype" is referenced from the folder where this script is being stored
- Top-left coordinates on specified image are recorded into X and Y variables
- Diagnostic messages let you know if the image could not be found on the screen, or there was an error retreiving your specific image file
- A GUI is created to pull in the specified image and record it's dimensions
- Dimensions of specified image are divided in half and added to the top-left found coordinates of the specified image to find centroid
- Cursor clicks on that coordinate (center of image), then the cursor moves to the top-left corner of your main monitor to ensure ImageSearch 
		is not spoofed from cursor hovering over specified image(s)
- This process takes less than 5 seconds to perform one iteration

HOW TO USE:

1. Type in your image file name inside quotations next to imagefilename := (e.g. imagefilename := "uglymonkey.png")
2. Set the hotkey you would like to designate to running this script. By default, it is your RIGHT ALT key. Feel free to change if necessary for your
purposes (e.g. If you want F4 to be the designated execution hotkey, change RAlt:: to F4::)
3. Ensure the image you are referencing is in the correct folder/directory. By default, it searches inside the folder where the script is located on 
your computer. If you want to change this to another location, remove %A_ScriptDir%\ and replace it with something like C:\Users\Tigerlily\
4. Ensure the image you are wanting to click on is in your Main Monitor, or ImageSearch will be unable to find the image.


LIMITATIONS:

- When using multiple monitors, it will only find an image in the monitor that you have set as your "Main Monitor". It will fail to find an image 
in external monitors. If anyone knows how to gracefully solve this limitation, please give me feedback! A potential workaround would be to 
disable all external monitors via Windows Display Settings, but I feel like that may be chunky and create a lack of fluidity for large scale projects
- ImageSearch within this script searches for an exact match and will not find the image if there is a slight variance in pixel color. If this is an 
issue for you, I beleive that adding *n after the file name within the ImageSearch command string adds a tolerance for more shades of
variation. n can = between 0 and 255, with 255 accepting all shades of colors.

NOTES:

-This is my first function that I created. I'm still a n00b at this point, but looking to grow my skills exponentially in the next year so I can 
automate my work and scale my business solutions across the company I currently work for.
- I don't understand global or local variables whatsoever, but the script would not run until set the mode as global and assigned those two 
variables as local variables. Anyone care to explain how that works? I've looked up the documentations but had no luck understanding it.
- If you think there is a way to improve this script to make it more efficient or accurate (from a coding optimization perspective and 
functionality perspective), I would love to hear your feedback and ideas! Thank you for reading and thank you for trying this one out!
		
		
*/

#SingleInstance, force ;	Doesn't allow the script to run multiple instances at once.
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. 
#Warn ; Enable warnings to assist with detecting common errors. 
SendMode Input ; Recommended for new scripts due to its superior speed and reliability. 
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. 


End::ExitApp
return

ClickImageCenter(imagefilename)
{
	global
	local ImageX, ImageY
CoordMode, Mouse, Client  ;
	ImageSearch, ImageX, ImageY, 0, 0, A_ScreenWidth, A_ScreenHeight, %A_ScriptDir%\%imagefilename%
		Sleep, 50
			if ErrorLevel = 2
				MsgBox Could not conduct the search - likely due to improper file storage or filename typos.
			else if ErrorLevel = 1
				MsgBox %imagefilename% could not be found on the screen.
			else					
				{
				image=%imagefilename%
				Guinum=69
				Gui, %Guinum%:Add, Picture, vImage, %image%
				GuiControlGet, Image, %Guinum%:Pos
				Gui, %Guinum%:Destroy
				}			
				
ImageXc := ImageX + ImageW/2
ImageYc := ImageY + ImageH/2

Click, %ImageXc%, %ImageYc%
MouseMove, 0, 0
}

RAlt::

imagefilename := "YourImageFileName.filetype"
ClickImageCenter(imagefilename)
Any feedback?
Last edited by Tigerlily on 13 Oct 2018, 21:35, edited 2 times in total.
-TL
CyL0N
Posts: 211
Joined: 27 Sep 2018, 09:58

Re: ClickImageCenter() - Accurately Clicks Image Centroid (No External Libraries)

13 Oct 2018, 13:55

First you ought to use code tags, second theres a number of highly optimised ImageSearch functions that return coordinates to which you can apply an offset if you find returned coordinates are not centered on image. Its a simpler, better & faster solution.

Just do a forum search for any of these,
  • FindText
    FindClick
    GdipImageSearch
,I can't link them as I'm on my phone right now...
Tigerlily wrote: I feel like many scripts are posted on here without enough context and it wastes peoples time as they look for a solution to their issues
and find nothing useful. This is why I'm going to go into detail about this very simple image center clicking script.
It's actually better to post a short,concise description, for any verbose explanation,use code comments.

Cheers...
live ? long & prosper : regards
User avatar
Tigerlily
Posts: 377
Joined: 04 Oct 2018, 22:31

Re: ClickImageCenter() - Accurately Clicks Image Centroid (No External Libraries)

15 Oct 2018, 12:26

Thank you for the feedback CyL0n. Since I'm new to the forums I didn't know how to use code tags, thanks for pointing that out.

I feel that those solutions are not as simple and straightforward as mine, that's why I made my own function instead, which seems pretty lightweight. What makes those other 3 options more highly optimized than my script for the purpose I'm using it for?

The next functionality I would like to do is to build out a screenshotting function that starts by clicking anywhere and when you move the cursor away from that epicenter, it creates a perfect square directly around that epicenter, then saves it to either a predefined folder or prompts a Save As window. That way taking images required to run this function would be quicker and easier.. and could probably be used in other scenarios. I like how the application Jing darkens the screen around the selected area and then allows you to adjust the width and heighth. I wonder how I would create something like this.. seems like it could be pretty simple but I haven't started tinkering with coding this out yet..
-TL
CyL0N
Posts: 211
Joined: 27 Sep 2018, 09:58

Re: ClickImageCenter() - Accurately Clicks Image Centroid (No External Libraries)

15 Oct 2018, 18:39

Tigerlily wrote:
15 Oct 2018, 12:26
Thank you for the feedback CyL0n. Since I'm new to the forums I didn't know how to use code tags, thanks for pointing that out.

I feel that those solutions are not as simple and straightforward as mine, that's why I made my own function instead, which seems pretty lightweight. What makes those other 3 options more highly optimized than my script for the purpose I'm using it for?

The next functionality I would like to do is to build out a screenshotting function that starts by clicking anywhere and when you move the cursor away from that epicenter, it creates a perfect square directly around that epicenter, then saves it to either a predefined folder or prompts a Save As window. That way taking images required to run this function would be quicker and easier.. and could probably be used in other scenarios. I like how the application Jing darkens the screen around the selected area and then allows you to adjust the width and heighth. I wonder how I would create something like this.. seems like it could be pretty simple but I haven't started tinkering with coding this out yet..
Welcome to the forums.
You might want to use these to make using bbcodes easier,https://autohotkey.com/board/topic/39250-easy-bbcode/ & BBCodes.ahk

Well my goto for ImageSearch FindText for example uses MachineCode,i.e 'compiled' C Functions for image search instead of built in ahk image search which makes it much faster(almost instant in most cases), but best of all it does not require an image file,but instead searches for image patterns encoded into monochromatic text(image is represented as text) that can be seamlessly integrated. So yeah specified functions might have some bulk,but with good reason in every case,more functionality.
live ? long & prosper : regards

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: KruschenZ and 64 guests