πŸ“œ ⬆️ ⬇️

Writing a bot for the game "Find the Difference"


Not long ago, I stumbled upon a game that I played many years ago. I think many in the search for differences broke their eyes for a long time. Today I decided to go through it again, but, to be honest, I was too lazy to go through it from 0. Therefore, I decided to write myself an assistant. The article will tell one of the solutions, not the best, but the most understandable for beginners. So, let's begin.

I wrote everything in python 2.7
PIL library used

from PIL import Image, ImageDraw 

')
Next, you need to describe all the functions and methods that we will use, so that everyone can understand the further code.

 image1 = Image.open("1.jpg") 

So we open the file we need.

 pix1 = image1.load() 

We write in pix1 the colors of all the pixels of the picture. Now, by the pixel coordinate, we can get its color.

 draw = ImageDraw.Draw(ANS) 

Create a drawing tool.

 image1.size 

Returns a pair (width and height of the image).

 draw.ellipse((x, y), (255, 255, 255)) 

Drawing a white point on the given coordinates.

 ANS.save("ans.png", "PNG") 

Save image in PNG format. If the full path is not specified, it is saved to the folder with the executable program.

 del draw 

Remove the β€œdraw” tool.

Getting down to the point ...

Open the files we want to compare.
 from PIL import Image, ImageDraw image1 = Image.open("1.jpg") #  β„– 1 image2 = Image.open("2.jpg") #  β„– 2 ANS = Image.open("1.jpg") #  


Now create a brush and unload all the pixel color data from the pictures.
 from PIL import Image, ImageDraw image1 = Image.open("1.jpg") #  β„– 1 image2 = Image.open("2.jpg") #  β„– 2 ANS = Image.open("1.jpg") #  draw = ImageDraw.Draw(ANS) pix1 = image1.load() pix2 = image2.load() 


It is necessary to determine the size of the images. Since they may differ slightly, we take the minimum of them, in order not to refer to non-existent pixels.
 from PIL import Image, ImageDraw image1 = Image.open("1.jpg") #  β„– 1 image2 = Image.open("2.jpg") #  β„– 2 ANS = Image.open("1.jpg") #  draw = ImageDraw.Draw(ANS) pix1 = image1.load() pix2 = image2.load() width = min(image1.size[0], image2.size[0]) height = min(image1.size[1], image2.size[1]) 


The last left. We will sort out the pixels and count the difference between their values.
 from PIL import Image, ImageDraw image1 = Image.open("2_1.jpg") image2 = Image.open("2_2.jpg") ANS = Image.open("2_1.jpg") draw = ImageDraw.Draw(ANS) pix1 = image1.load() pix2 = image2.load() width = min(image1.size[0], image2.size[0]) height = min(image1.size[1], image2.size[1]) eps = 30 for i in range(width): for j in range(height): dx1 = pix1[i, j][0] - pix2[i, j][0] dx2 = pix1[i, j][1] - pix2[i, j][1] dx3 = pix1[i, j][2] - pix2[i, j][2] draw.point((i, j), (abs(dx1), abs(dx2), abs(dx3))) #        . ANS.save("ans.jpg", "JPEG") del draw 





















If to correct the code a little.

Source: https://habr.com/ru/post/163565/


All Articles