Based on OpenCV to realize the puzzle version of the mini-game for your reference, the details are as follows
Effective demonstration
realization
reasoning
1. Segment the image into m*n subgraphs
2. Disrupting the order of subgraphs
3. Recompose the sub-pictures into a new picture and display it.
4. Add a mouse click response action to exchange the position of the two charts clicked by the mouse in turn
5. After each exchange, determine whether it is consistent with the original picture or not
python code
import cv2 as cv import numpy import random import math src = ("D:\\CvPic\\") print() h = [0] w = [1] c = [2] row = 3 col = 3 offset_h = h/row offset_w = w/col firstClick = False clickIdx = [0,0] tileList = [] def calPicIdx(x, y): print(str(y)+" "+str(h/col)) i = y//(offset_h) print(str(y%offset_h)+" "+str(offset_w)) j = ((x%w)/offset_w) idx = i*row+j print("i:"+str(i)+" j:"+str(j)+" idx:"+str(idx)) return int(idx) def onMouse(event, x, y, flag ,params): if event==cv.EVENT_LBUTTONDOWN: print("left button down:"+str(x)+" "+str(y)) idx = calPicIdx(x, y) global firstClick firstClick = not firstClick print(firstClick) if firstClick: clickIdx[0] = idx else: clickIdx[1] = idx tileList[clickIdx[0]], tileList[clickIdx[1]] = tileList[clickIdx[1]], tileList[clickIdx[0]] for i in range(0, row): for j in range (0, col): dst[i*offset_h:(i+1)*offset_h-1, j*offset_w:(j+1)*offset_w-1] = tileList[i*row+j] ("dst", dst) difference = (dst, src2) result = not (difference) #if difference is all zeros it will return False print("result:"+str(result)) print(clickIdx) # --------------splite image into n*n tile-------------- tile = ((offset_h-1, offset_w-1, c),numpy.uint8) for i in range(0, row): for j in range (0, col): tile = src[i*offset_h:(i+1)*offset_h-1, j*offset_w:(j+1)*offset_w-1] (tile) # ("tile", tile) # --------------ramdom the tiles-------------------- print(len(tileList)) for i in range(len(tileList)-1,0,-1): randomIdx = (0,i-1) print("swap:"+str((0,i-1))+" "+str(i)) tileList[i], tileList[randomIdx] = tileList[randomIdx], tileList[i] # debug show every tile # for k,tile in enumerate(tileList): # ("tile"+str(k), tile) dst = ((h, w, c), numpy.uint8) for i in range(0, row): for j in range (0, col): dst[i*offset_h:(i+1)*offset_h-1, j*offset_w:(j+1)*offset_w-1] = tileList[i*row+j] ("dst") ("dst", onMouse) ("dst", dst) # -------------match the origin image and now-------------- src2 = () for i in range(1, row): src2[i*offset_h-1:i*offset_h]= ((1,w,3), numpy.uint8) for j in range(1, col): src2[0:h,j*offset_w-1:j*offset_w]= ((h,1,3), numpy.uint8) # ("src2", src2) (0)
consultation
90's classic "hand game" - puzzle board game Opencv implementation
This is the entire content of this article.