Skip to content

Instantly share code, notes, and snippets.

@aferral
Last active March 19, 2017 13:38
Show Gist options
  • Save aferral/588bed4f10a6f181398470a91ae3cf26 to your computer and use it in GitHub Desktop.
Save aferral/588bed4f10a6f181398470a91ae3cf26 to your computer and use it in GitHub Desktop.
Select pixels in image and save them to pickles
import cv2
import numpy as np
import os
import pickle
#----------------------INICIO PARAMETROS
imagesFolder = "C:/Users/andres/Desktop/CrackImages/CleanCracks"
dataOutFolder = "C:/Users/andres/Desktop/CrackImages/saved"
imageTypes = ['jpeg']
imageDim = 96
startAt = 1800
#----------------------FIN PARAMETROS
factor=5
if not os.path.exists(dataOutFolder):
os.makedirs(dataOutFolder)
imageList = []
for impath in os.listdir(imagesFolder):
if impath.split('.')[-1] in imageTypes:
imageList.append(impath)
imageList.sort(key=lambda x : int(x.split('.')[0]))
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1
imgLeft = None
imgRight = None
current = startAt
mascaraTemp = None
# mouse callback function
def addSquare(square):
global imgRight,imgLeft,mascaraTemp, current
square = map(lambda x: int(x / factor), list(square))
print 'using square ',square
#Crezco la mascara
mascaraTemp[int(square[2]):int(square[3]), int(square[0]):int(square[1])] = True
imageActiva = imageList[current]
imgOr = cv2.imread(os.path.join(imagesFolder, imageActiva))
#pintar azul donde se debe
imgLeft = imgOr.copy()
imgLeft[mascaraTemp,:] = (255,0,0)
#Laa imagen de la derecha es el trozo
derp = np.zeros((imgOr.shape))
derp[:,:,0] = mascaraTemp.astype(np.int8) * imgOr[:,:,0]
derp[:, :, 1] = mascaraTemp.astype(np.int8) * imgOr[:,:,1]
derp[:, :, 2] = mascaraTemp.astype(np.int8) * imgOr[:,:,2]
# imgRight[mascaraTemp,0] = imgOr[mascaraTemp,0]
# imgRight[mascaraTemp, 1] = imgOr[mascaraTemp, 1]
# imgRight[mascaraTemp, 2] = imgOr[mascaraTemp, 2]
# imgRight[mascaraTemp, :] = imgOr[mascaraTemp, :]
derp = derp.astype(np.uint8)
imgRight = derp
imgLeft = cv2.resize(imgLeft, (0, 0), fx=factor, fy=factor)
imgRight = cv2.resize(derp, (0, 0), fx=factor, fy=factor)
def paintPixels(event, x, y, flags, param):
global ix,iy,drawing,mode,imgLeft, mascaraTemp
sizze = cv2.getTrackbarPos("Brush size", 'image')
square = (x - sizze * 0.5, x + sizze * 0.5, y - sizze * 0.5, y + sizze * 0.5)
#TODO record PAINTED PIXELS
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_RBUTTONDOWN:
check()
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
addSquare(square)
else:
addSquare(square)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode == True:
addSquare(square)
else:
addSquare(square)
def check():
global current, imgLeft, mascaraTemp, imgRight
imageActiva = imageList[current]
#*********ACA VEO SI DEBO GUARDAR RESETEAR O NO GUARDAR LA IMAGEN ACTUAL Y SUS CAMBIOS
imageName = "".join(imageActiva.split('.')[:-1])
savedFile = os.path.join(dataOutFolder, imageName+'.pkl')
switch = cv2.getTrackbarPos('DC/R/S', 'image')
dontsave = (switch == 0)
reset = (switch == 1)
save = (switch == 2)
if reset:
os.remove(savedFile)
elif save:
with open(savedFile, 'wb+') as f:
pickle.dump([mascaraTemp], f)
elif dontsave:
pass
#*************Ahora paso a la siguiente imagen***********************
delta = cv2.getTrackbarPos('Prev/Next', 'image')
current = current + 1 if (delta == 1) else current - 1
imageActiva = imageList[current]
imgNochanges = cv2.imread(os.path.join(imagesFolder, imageActiva))
print "current ", current, " ", imageActiva
print imageList[current:current+2]
print imageList[0]
print imageList[-1]
#*********************** TODO chequear que no tenga archivo (crearlo) en otro caso mostrar imagen resaltada
imageName = "".join(imageActiva.split('.')[:-1])
savedFile = os.path.join(dataOutFolder, imageName+'.pkl')
if not os.path.exists(savedFile):
print "No existia archivo-imagen lo creo"
with open(savedFile, 'wb+') as f:
pickle.dump([np.zeros((imageDim,imageDim))], f)
with open(savedFile,'rb') as f:
datos = pickle.load(f)
mascaraTemp = datos[0].astype(np.bool)
#agarrar esos pixeles y colocar en imagen 2
image2 = np.zeros(imgNochanges.shape)
image2[mascaraTemp,:] = imgNochanges[mascaraTemp,:]
# image2[0:10,0:10, :] = (255,0,0)
#En imagen 1 pintar imagen azul en esas cordenadas
imgNochanges[mascaraTemp,:] = (255,0,0)
# Expandir imagenes y colocar en gobal correpondiente
imgLeft = cv2.resize(imgNochanges, (0, 0), fx=factor, fy=factor)
imgRight = cv2.resize(image2,(0,0),fx=factor,fy=factor)
def nothing(delta):
pass
#Izquierda imagen original
cv2.namedWindow('image')
cv2.createTrackbar('Prev/Next','image',0,1,nothing)
cv2.createTrackbar('Brush size','image',0,10,nothing)
cv2.createTrackbar('DC/R/S','image',0,2,nothing)
cv2.setMouseCallback('image', paintPixels)
check()
# Derecha pixeles seleccionados
cv2.namedWindow('image2')
while(1):
cv2.imshow('image', imgLeft)
cv2.imshow('image2', imgRight)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment