Examples of using nested looping to more efficiently perform picture manipulations.
Download Complete Example
import time
import media
def nested_loop_test():
for outer_number in range(4):
print("outer loop:", outer_number)
for inner_number in range(3):
print("\tinner loop:", inner_number)
print('---------------------------')
def slow_remove_color(image, tl_x, tl_y, br_x, br_y):
new_image = media.duplicatePicture(image)
for pixel in media.getPixels(new_image):
x = media.getX(pixel)
y = media.getY(pixel)
if tl_x <= x <= br_x and tl_y <= y <= br_y:
pixel = media.getPixel(new_image, x, y)
red = media.getRed(pixel)
green = media.getGreen(pixel)
blue = media.getBlue(pixel)
lum = (red + green + blue) // 3
media.setColor(pixel, media.makeColor(lum, lum, lum))
return new_image
def fast_remove_color(image, tl_x, tl_y, br_x, br_y):
new_image = media.duplicatePicture(image)
for x in range(tl_x, br_x):
for y in range(tl_y, br_y):
pixel = media.getPixel(new_image, x, y)
red = media.getRed(pixel)
green = media.getGreen(pixel)
blue = media.getBlue(pixel)
lum = (red + green + blue) // 3
media.setColor(pixel, media.makeColor(lum, lum, lum))
return new_image
def mirror_picture(image):
new_image = media.duplicatePicture(image)
width = media.getWidth(image)
height = media.getHeight(image)
for x in range(width):
for y in range(height//2):
dest_pixel = media.getPixel(new_image, x, y)
source_pixel = media.getPixel(new_image, x, (height-1) - y)
source_color = media.getColor(source_pixel)
media.setColor(dest_pixel, source_color)
return new_image
def fix_door(image):
new_image = media.duplicatePicture(image)
start_x = 28
for x in range(411, 541):
start_y = 148
for y in range (147, 519):
source_pixel = media.getPixel(new_image, x, y)
dest_pixel = media.getPixel(new_image, start_x, start_y)
media.setColor(dest_pixel, media.getColor(source_pixel))
start_y += 1
start_x += 1
return new_image
nested_loop_test()
nes_controller = media.makePicture('images/nes.jpg')
start_time = time.perf_counter_ns()
edit = slow_remove_color(nes_controller, 393, 227, 440, 265)
print("seconds:", (time.perf_counter_ns() - start_time)/1E9)
media.show(edit)
start_time = time.perf_counter_ns()
edit = fast_remove_color(nes_controller, 393, 227, 440, 265)
print("seconds:", (time.perf_counter_ns() - start_time)/1E9)
media.show(edit)
green_doors = media.makePicture('images/green-doors-small.jpg')
media.show(green_doors)
media.show(fix_door(green_doors))
ps4_controller = media.makePicture('images/ps4.jpg')
media.show(ps4_controller)
media.show(mirror_picture(ps4_controller))
media.quit()