J-Filters V

This filter runs an edge detection algorithm on a given image.
For demonstration I used – as in my previous filter posts – an image from my post Stacking Stones.
The original image
The image with applied edge detection filter:
The edge detected version


# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech 3rd of February, 2016
#         edited 5th of February, 2016

# importing needed modules
import pygame, sys, time, math, os, random

""" FUNCTIONS """
# gets the value at given position
def getVal(pos):
	try:
		c = G.IMG.get_at(pos)
		c = (c[0] + c[1] + c[2]) / 3.
	except:
		c = 255
	return c

""" GAME """
# game class
class GAME():
	# initialize program
	def __init__(self):
		# load image
		self.IMG = pygame.image.load("original.jpg")
		# get image's size
		rct = self.IMG.get_rect()

		self.WIDTH, self.HEIGHT = rct.right, rct.bottom
		self.SIZE = [self.WIDTH, self.HEIGHT]
		self.SURF = pygame.Surface(self.SIZE)
		self.SCREEN = pygame.display.set_mode(self.SIZE)

		self.TICKS = 0
		self.RUNNING = True

		# I defines current image filter position
		self.I = 0

		# functions
		pygame.display.set_caption("Edge Detection Filter")
	
	# tick function
	def tick(self):
		# handle events
		for event in pygame.event.get():
			# quit program
			if event.type == pygame.QUIT:
				self.quit()
			
			# save screenshot
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE:
					self.screenshot()

		# for loop
		for _ in range(0, 1000):
			if self.I < self.WIDTH * self.HEIGHT:
				# get x and y position
				x, y = self.I % self.WIDTH, self.I / self.WIDTH
				
				# calculate Gx and Gy
				Gx, Gy = 0, 0

				Gx += getVal([x-1, y-1]) * -1
				Gx += getVal([x-1, y]) * -2
				Gx += getVal([x-1, y+1]) * -1
				Gx += getVal([x+1, y-1]) * 1
				Gx += getVal([x+1, y]) * 2
				Gx += getVal([x+1, y+1]) * 1

				Gy += getVal([x-1, y-1]) * -1
				Gy += getVal([x, y-1]) * -2
				Gy += getVal([x+1, y-1]) * -1
				Gy += getVal([x-1, y-1]) * 1
				Gy += getVal([x, y-1]) * 2
				Gy += getVal([x+1, y-1]) * 1

				# calculate G
				G = math.sqrt(Gx**2 + Gy**2)
				G = 255. / math.sqrt((255*4)**2 + (255*4)**2) * G
				G = int(G)

				# set color
				self.SURF.set_at([x, y], [G, G, G])
				
				# removed code
				"""C = self.IMG.get_at([x, y])
				C = [int(C[0] * G/255.), int(C[1] * G/255.), int(C[2] * G/255.)]
				self.SURF.set_at([x, y], C)/255."""

				# increment running variable
				self.I += 1

	# render function
	def render(self):
		# blit and flip
		self.SCREEN.blit(self.SURF, [0, 0])
		pygame.display.flip()
	
	# quits
	def quit(self):
		self.RUNNING = False

	# takes a screenshot
	def screenshot(self):
		path = os.getcwd() + "/out/"
		
		try:
			if not os.path.isdir(path):
				os.mkdir(path)
			
			name = "img" + str(len(os.listdir(path))) + ".png"
			pygame.image.save(self.SURF, path + name)
		except:
			pass

	# run function (uses tick() and render())
	def run(self):
		ticksPerSecond = 60
		lastTime = time.time() * 1000000000
		nsPerTick =  1000000000.0 / float(ticksPerSecond)
	
		ticks = 0
		frames = 0
	
		lastTimer = time.time() * 1000
		delta = 0.0
		
		while self.RUNNING:
			now = time.time() * 1000000000
			delta += float(now - lastTime) / float(nsPerTick)
			lastTime = now
			shouldRender = False
					
			while delta >= 1:
				ticks += 1
				self.TICKS += 1
				self.tick()
				delta -= 1
				shouldRender = True
			
			if shouldRender:
				frames += 1
				self.render()
			
			if time.time() * 1000 - lastTimer >= 1000:
				lastTimer += 1000
				
				# debug
				# print("Frames: " + str(frames) + ", ticks: " + str(ticks))
			
				frames = 0
				ticks = 0

# start game
G = GAME()
G.run()
Advertisements

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