On completion of this unit the student should be able to design working modules in response to solution requirements, and use a programming or scripting language to develop the modules
We will be using Grok Learning as the main lesson sequence in learning the programming language Python. This will be extended with examples using Easygui and the Python Image Library
Python is the most popular language for 1st year university courses, for data science and machine learning (artificial intelligence). It is also running the back-end of many of the larger websites on the internet. It is a good first language to learn and has a lot of utility. Python is also Free software (i.e., costs no money and is open source) and the primary implementation is available at Python.org
>>> import easygui
>>> easygui.egdemo() # opens menu to demo all functionality
Easygui allows for easy sequential input and output (just like the text-based programs using input
and print
statements)
>>> import easygui
>>> name = easygui.enterbox(msg='What is your name?',
title='Hi there!')
>>> easygui.msgbox(msg='Nice to meet you, {}'.format(name))
'OK'
Notes:
.load()
method to get pixel array, faster than using .getpixel
for each pixel. Grok's image manipulation course uses the latter method, but is still a good resource.Basic pixel-level image manipulation example on the old-old FCC logo
from PIL import Image
# Basic example showing how to open a file
# Read properties of image, Read & write pixels, Save
# Open an image in same directory as Python script
img = Image.open("FCC.png")
# Print some properties of the image
print(img.filename, img.size, img.mode)
# Display image using default image viewer of OS
img.show()
# Access a 2D pixel array for the image
pix = img.load()
# Read of a pixel near the middle
print(pix[100, 60])
# Set a block of pixels near the middle white
pix[100, 60] = (255, 255, 255)
pix[101, 60] = (255, 255, 255)
pix[100, 61] = (255, 255, 255)
pix[101, 61] = (255, 255, 255)
img.show()
# Loop over ALL pixels
# Set every second horizontal line grey
for x in range(img.size[0]):
for y in range(img.size[1]):
if y % 2 == 0:
pix[x, y] = (127, 127, 127)
img.show()
# Save changes to a new file
new_filename = img.filename[:-4]
+ "stripy"
+ img.filename[-4:]
img.save(new_filename)