from matplotlib.widgets import RectangleSelector import matplotlib.pyplot as plt from random import randint import numpy as np import cv2 import time from function import * def reScale(img,scale): height, width = img.shape[:2] new_height = int(height / scale) new_width = int(width / scale) scaled_img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_AREA) return scaled_img, new_height,new_width def reScaleCoord(oWidth,oHeight,nWidth,nHeight,x1,y1,x2,y2): x1, x2 = int(x1*nWidth/oWidth),int(x2*nWidth/oWidth) y1, y2 = int(y1*nHeight/oHeight),int(y2*nHeight/oHeight) return x1,y1,x2,y2 def getDist(pValue1, pValue2): return np.sum((pValue1 - pValue2) ** 2) def getRandomPatch(img2,pSize,x1,y1,x2,y2): height, width = img2.shape[:2] x = [randint(0,x1),randint(x2,width-pSize)][randint(0,1)] y = [randint(0,y1),randint(y2,height-pSize)][randint(0,1)] patch = getZoneFromCoord(x,y,pSize) return patch def getValueFromPatch(img,patch,pSize): ret = img[patch[0][1]:patch[0][1]+pSize,patch[0][0]:patch[0][0]+pSize] ret = ret.transpose(1, 0, 2) return ret.reshape(-1, 3) def applyPatch(img,zone,patchValue): for i in range(len(zone)) : img[zone[i][1],zone[i][0]] = patchValue[i] return img def findBestPatchFromNeigbour(zoneValue,oDist,patch,offset,height,width,img,pSize): neigbour = [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[0,1],[1,0],[1,1]] trouve = False rP = patch for x,y in neigbour: p = patch.copy() p[:,0] += x*offset p[:,1] += y*offset if np.any(p < 0) or np.any(p[:,0] >= width) or np.any(p[:,1] >= height): continue value = getValueFromPatch(img,p,pSize) dist = getDist(zoneValue,value) if (dist < oDist): trouve = True oDist = dist rP = p return trouve, rP, oDist def findBestPatch(img2,zone,zoneValue,pSize,pixSize,height,width,x1,y1,x2,y2): if not (x1<=zone[0][0]<=x2 and y1<=zone[0][1]): patch = zone.copy() return patch patch = getRandomPatch(img2,int(pSize/pixSize)*2,x1,y1,x2,y2) pValue = getValueFromPatch(img2,patch,pSize) pdist = getDist(zoneValue,pValue) for i in range(500): tpatch = getRandomPatch(img2,int(pSize/pixSize)*2,x1,y1,x2,y2) tpValue = getValueFromPatch(img2,tpatch,pSize) tpdist = getDist(zoneValue,tpValue) if tpdist