Have you ever wondered what color was there on the image you were browsing some day on the web ?
You download the image. Search an image picker on the web and then upload your image there! So tedious and long process!

You can do that programmatically via Python, and that too very very easily. As we have been posting NPTEL Answers of Python, we thought it would be good to see how Python can be used in our daily life to solve some easy problems or tasks.

First of all, we need to install a module named ‘pyautogui’.

Navigate to the folder where Python is installed and open Command Prompt and execute the following command there:-

python -m pip install pyautogui

You should get the following screen after successful installation of the module.

If you have any problems while installing, you can refer to the link here (https://pyautogui.readthedocs.io/en/latest/install.html) or comment below and we will try our best to solve your issue.

Program : ( Click here to download )

import pyautogui
import time

def print_no_newline(string):
    import sys
    sys.stdout.write("\r")
    sys.stdout.write(string)
    sys.stdout.flush()

try:
    while True:
        x, y = pyautogui.position()
        pixelColor = pyautogui.screenshot().getpixel((x, y))
        ss = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        ss += ' RGB: (' + str(pixelColor[0]).rjust(3)
        ss += ', ' + str(pixelColor[1]).rjust(3)
        ss += ', ' + str(pixelColor[2]).rjust(3) + ')'
        print_no_newline(ss)
        time.sleep(1.0)

except KeyboardInterrupt:
    print("\nDone...")

Explanation :

print_no_newline function does a very simple task : Prints again on the same line instead of moving on to the next line.

pyautogui.position() gives us position of cursor on screen ( in form of tuple).

pyautogui.screenshot() provides us with current screenshot of full screen.

getpixel() method is used to get information about a particular pixel.

How to run :-

Save this code on your computer in any file ‘filename.py’. Open Command Prompt, go to directory where Python is installed and type “python filename.py” to execute code and see magic happen in the commandline.

You can press “Ctrl + C” to abort the program anytime.


Share your experience with us in the comments section or if you are having any problem executing this code.

Categories: Python