Example #1
0
def test_return_imgs(
):  # Tests that the number of images returned from translate is correct
    test_img = imread("../tests/imgs/milad.jpg")
    returned_arr_1a = mir.mirror("../tests/imgs/milad.jpg",
                                 "horizontal")  # should return 1 image
    returned_arr_1b = mir.mirror("../tests/imgs/milad.jpg",
                                 "vertical")  # should return 1 image
    returned_arr_2a = mir.mirror("../tests/imgs/milad.jpg",
                                 "all")  # should return 2 images
    returned_arr_2b = mir.mirror(
        "../tests/imgs/milad.jpg")  # all is default, should return 2 images

    assert returned_arr_1a.shape[
        0] == 2  # check two image in array (original and mirrored)
    assert returned_arr_1b.shape[
        0] == 2  # check two image in array (original and mirrored)
    assert returned_arr_2a.shape[
        0] == 3  # check three images in array (original and mirrored both directions)
    assert returned_arr_2b.shape[
        0] == 3  # check three images in array (original and mirrored both directions)
    assert returned_arr_1a.shape[
        1:] == test_img.shape  # check that returned image shapes same as input image shape

    assert np.all(returned_arr_1a[1, :, 1] == test_img[:, (
        test_img.shape[1] -
        2)])  # check that image is correctly mirrored horizontally
    assert np.all(returned_arr_1b[1, 1, :] == test_img[(
        test_img.shape[0] -
        2), :])  # check that image is correctly mirrored vertically
    assert np.all(returned_arr_2b[1, :, 1] == test_img[:, (
        test_img.shape[1] - 2)])  # check horizontal image mirroring on 'all'
    assert np.all(returned_arr_2b[2, 1, :] == test_img[(
        test_img.shape[0] - 2), :])  # check vertical image mirroring on 'all'
Example #2
0
def test_inputs():
    with pytest.raises(TypeError):
        mir.mirror("../tests/imgs/milad.jpg", 7)  # direction must be string
    with pytest.raises(TypeError):
        mir.mirror(True, "horizontal")  # image path must be a string

    with pytest.raises(ValueError):
        mir.mirror("../tests/imgs/milad.jpg",
                   "h")  # Not a valid string option for direction

    with pytest.raises(FileNotFoundError):
        mir.mirror("../tests/imgs/Path.jpg"
                   )  # Incorrect directory/file not in location
    def run(self):
        print("Connexion de %s %s" % (
            self.ip,
            self.port,
        ))
        import mirror
        try:
            while True:
                # Récupération header
                # Il faut avertir le serveur de la quantité de donnée à récupérer
                header = clientsocket.recv(20)
                fps = unpack(">f", header[0:4])[0]
                width = unpack(">f", header[4:8])[0]
                height = unpack(">f", header[8:12])[0]
                size = unpack(">q", header[12:20])[0]

                try:
                    # Récupération de la frame + aussitôt rebond vers le poste de commandement
                    size = unpack(">q", header[12:20])[0]
                    print("size = {}".format(size))
                    frame = read_from_socket(clientsocket, size)
                    print("fps = {} width = {} height = {} size = {}".format(
                        fps, width, height, size))
                    frame = numpy.ndarray((int(width), int(height), 3),
                                          dtype="uint8",
                                          buffer=frame)
                    mirror.mirror(frame)


#                except ConnectionAbortedError:
#                    break

                except:
                    print("Erreur dans la récupération")
                    print("len(bdata) = {}".format(len(frame)))
                    break

            print("Client déconnecté...")

        except Exception as e:
            print("ERROR!", sys.exc_info())
Example #4
0
    def mirror(self, tables, dest_url):
        """
        miror a set of `tables` from `dest_url`

        Returns a new Genome object

        Parameters
        ----------

        tables : list
            an iterable of tables

        dest_url: str
            a dburl string, e.g. 'sqlite:///local.db'
        """
        from mirror import mirror
        return mirror(self, tables, dest_url)
Example #5
0
    def mirror(self, tables, dest_url):
        """
        miror a set of `tables` from `dest_url`

        Returns a new Genome object

        Parameters
        ----------

        tables : list
            an iterable of tables

        dest_url: str
            a dburl string, e.g. 'sqlite:///local.db'
        """
        from mirror import mirror
        return mirror(self, tables, dest_url)
Example #6
0
def extract_patches(filename, patch_size, stride):

    image = cv.imread(filename)
    original_shape = image.shape
    image = mirror.mirror(image, padding, output_w)
    # switch bgr to rgb
    image = np.dstack((image[:, :, 2], image[:, :, 1], image[:, :, 0]))

    target = FLAGS.target_image_path
    target = cv.imread(target)
    b, g, r = cv.split(target)  # get b,g,r
    target = cv.merge([r, g, b])

    # pad array
    # centreIndexRow = int((size_input_patch[0] - size_input_patch[0])/2)
    # centreIndexCol = int((size_input_patch[1] - size_input_patch[1])/2)
    centreIndexRow = 0
    centreIndexCol = 0
    padrow = centreIndexRow + 2 * stride[0]
    padcol = centreIndexCol + 2 * stride[1]

    #image = np.lib.pad(image, ((padrow, padrow), (padcol,padcol), (0,0)), 'symmetric')

    rowRange = range(0, (image.shape[0] - patch_h) + 1, stride[0])
    colRange = range(0, (image.shape[1] - patch_w) + 1, stride[1])
    nPatches = len(rowRange) * len(colRange)

    patches = np.empty([nPatches, patch_h, patch_w, image.shape[2]],
                       dtype=image.dtype)

    for index1, row in enumerate(rowRange):
        for index2, col in enumerate(colRange):

            patch1 = image[row:row + FLAGS.train_image_target_size,
                           col:col + FLAGS.train_image_target_size, :]
            patch1 = stain_norm.norm_rn(patch1, target)
            patches[(index1 * len(colRange)) + index2, :, :] = patch1

    return patches, image.shape, original_shape
Example #7
0
from mirror import mirror
from mirror.visualisations import *
from PIL import Image
from torchvision.models import resnet101, resnet18, vgg16, alexnet
from torchvision.transforms import ToTensor, Resize, Compose

# create a model
model = vgg16(pretrained=True)
# open some images
cat = Image.open("./cat.jpg")
dog_and_cat = Image.open("./dog_and_cat.jpg")
# resize the image and make it a tensor
to_input = Compose([Resize((224, 224)), ToTensor()])
# call mirror with the inputs and the model
mirror([to_input(cat), to_input(dog_and_cat)],
       model,
       visualisations=[DeepDreamVis, BackPropVis, GradCamVis])
    def __call__(self, inputs, layer, repeat=1):
        return inputs.repeat(repeat, 1, 1, 1), None


params = {
    'repeat': {
        'type': 'slider',
        'min': 1,
        'max': 100,
        'value': 2,
        'step': 1,
        'params': {}
    }
}

visualisation = partial(WebInterface.from_visualisation,
                        RepeatInput,
                        params=params,
                        name='Visualisation')
# create a model
model = vgg16(pretrained=True)
# open some images
cat = Image.open("./cat.jpg")
dog_and_cat = Image.open("./dog_and_cat.jpg")
# resize the image and make it a tensor
to_input = Compose([Resize((224, 224)), ToTensor()])
# call mirror with the inputs and the model
mirror([to_input(cat), to_input(dog_and_cat)],
       model,
       visualisations=[visualisation])
Example #9
0
from mirror import mirror
from mirror.visualisations import *

from PIL import Image

from torchvision.models import resnet101, resnet18, vgg16
from torchvision.transforms import ToTensor, Resize, Compose

# create a model
model = vgg16(pretrained=True)

cat = Image.open("./cat.jpg")
# resize the image and make it a tensor
input = Compose([Resize((224, 224)), ToTensor()])(cat)
# add 1 dim for batch
input = input.unsqueeze(0)
# call mirror with the input and the model
mirror(input, model, visualisations=[DeepDream])
Example #10
0
 def mirror(self, tables, dest_url):
     from mirror import mirror
     return mirror(self, tables, dest_url)
Example #11
0
from mirror import mirror
from mirror.visualisations import *
from PIL import Image
from torchvision.models import resnet101, resnet18, vgg16, alexnet
from torchvision.transforms import ToTensor, Resize, Compose

# create a model
model = vgg16(pretrained=True)
# get an image
cat = Image.open("./cat.jpg")
# resize the image and make it a tensor
input = Compose([Resize((224, 224)), ToTensor()])(cat)
# add 1 dim for batch
input = input.unsqueeze(0)
# call mirror with the input and the model
mirror(input, model, visualisations=[DeepDreamVis, BackPropVis, GradCamVis])
Example #12
0
#                      'type' : 'slider',
#                      'min' : 1,
#                      'max' : 100,
#                      'value' : 2,
#                      'step': 1,
#                      'params': {}
#                  }
#         }
#
# vis = RepeatInput(params, 'repeat')
# print(vis.to_JSON())
# print(vis.from_JSON({ 'repeat' : { 'value' : 2}}))
# print(vis.to_JSON())

from mirror import mirror
from PIL import Image
from torchvision.models import vgg16
from torchvision.transforms import ToTensor, Resize, Compose

# create a model
model = vgg16(pretrained=True)
# open some images
cat = Image.open("../cat.jpg")
dog_and_cat = Image.open("../dog_and_cat.jpg")
# resize the image and make it a tensor
to_input = Compose([Resize((224, 224)), ToTensor()])
# call mirror with the inputs and the model
mirror([to_input(cat), to_input(dog_and_cat)],
       model,
       visualisations=[RepeatInput])
Example #13
0
 def mirror(self, tables, dest_url):
     from mirror import mirror
     return mirror(self, tables, dest_url)
Example #14
0
from mirror import mirror
from mirror.visualisations.web import *
from PIL import Image
from torchvision.models import resnet101, resnet18, vgg16, alexnet
from torchvision.transforms import ToTensor, Resize, Compose

# create a model
model = vgg16(pretrained=True)
# open some images
cat = Image.open("./cat.jpg")
dog_and_cat = Image.open("./dog_and_cat.jpg")
# resize the image and make it a tensor
to_input = Compose([Resize((224, 224)), ToTensor()])
# call mirror with the inputs and the model
mirror([to_input(cat), to_input(dog_and_cat)],
       model,
       visualisations=[BackProp, GradCam, DeepDream],
       port=3001,
       debug=True)
Example #15
0
def minimiser(aut):
    return determiniser(mirror(determiniser(mirror(aut))))
Example #16
0
FILE_17_4 = '/home/lenovo/256Gdisk/juesai/2017_4/'
e_17_4 = '/home/lenovo/256Gdisk/juesai/enhance/e17_4/'
m_17_4 = '/home/lenovo/256Gdisk/juesai/enhance/m17_4/'

nor_15_3 = '/home/lenovo/256Gdisk/juesai/enhance/normal/15_3/'
nor_15_4 = '/home/lenovo/256Gdisk/juesai/enhance/normal/15_4/'
nor_17_3 = '/home/lenovo/256Gdisk/juesai/enhance/normal/17_3/'
nor_17_4 = '/home/lenovo/256Gdisk/juesai/enhance/normal/17_4/'

#label
png_file = "/home/lenovo/256Gdisk/juesai/label_png/"
roated_file = "/home/lenovo/256Gdisk/juesai/enhance/elabel/"
mirror_file1 = "/home/lenovo/256Gdisk/juesai/enhance_4/train/annotations/training/"
mirror_file2 = "/home/lenovo/256Gdisk/juesai/enhance_3/train/annotations/training/"
enhance1.enhance(png_file, roated_file)
mirror.mirror(roated_file, mirror_file1)
mirror.mirror(roated_file, mirror_file2)

wky_test.roate(FILE_15_3, e_15_3)
wky_test.mirror(e_15_3, m_15_3)
wky_test.roate(FILE_15_4, e_15_4)
wky_test.mirror(e_15_4, m_15_4)
wky_test.roate(FILE_17_3, e_17_3)
wky_test.mirror(e_17_3, m_17_3)
wky_test.roate(FILE_17_4, e_17_4)
wky_test.mirror(e_17_4, m_17_4)

mean_15_3, var_15_3, mean_15_4, var_15_4, mean_17_3, var_17_3, mean_17_4, var_17_4 = calmeanvar.cal(
    FILE_2017, FILE_2015)
#normal 15 17 3 4
normal(m_15_3, nor_15_3, mean_15_3, var_15_3)
def angulo_dominante_fix(rho,theta,x_cm, y_cm,debug=0):

    vector = np.arange(360)
    vector.resize(1,360)

    maxi = np.amax(rho)
    indice = np.argmax(rho)
    
    u,v=cv2.polarToCart(maxi,indice*math.pi/180)
    
    u=float(u[0])
    v=float(v[0])
    
    #Angulo dominante espejo
    mRHO = rho.copy()
    
    mRHO = mirror(indice, mRHO)
    
    maxi2 = np.max(mRHO)
    indice2 = np.argmax(mRHO)
    
    [u2,v2]=cv2.polarToCart(maxi2,indice2*math.pi/180)
    
    u2=float(u2[0])
    v2=float(v2[0])
    
    vec_max = np.array([u,v],dtype='float')
    vec_mirror = np.array([u2,v2],dtype='float')
    vec_centermass = np.array([x_cm,-y_cm],dtype='float')
    
    if not maxi2>=maxi*.7:
        angulodominante = indice
        return angulodominante
#    [u3,v3] = cv2.cartToPolar(vec_centermass[0],vec_centermass[1])
#    u3=float(u3[0])
#    v3=(float(v3[0])*180/math.pi)-90
#    
#    [u4,v4]=cv2.polarToCart(u3,v3*math.pi/180)
#        
#    u4=float(u4[0])
#    v4=float(v4[0])
#    
#    vec_centermass = np.array([u4,v4],dtype='float')
    ################################################################################
    # probe normalizando los vectores, ya que la diferencia de magnitudes era muy grande
#    vec_max = normalize(vec_max.reshape(1,-1), axis=1).ravel()
#    vec_mirror = normalize(vec_mirror.reshape(1,-1), axis=1).ravel()
#    vec_centermass = normalize(vec_centermass.reshape(1,-1), axis=1).ravel()
    
    #en este caso no se normaliza
#    vec_max = vec_max.reshape(1,-1).ravel()
#    vec_mirror = vec_mirror.reshape(1,-1).ravel()
#    vec_centermass = vec_centermass.reshape(1,-1).ravel()
    ################################################################################
    
    # Proyecciones
    projection_max = np.dot(vec_centermass,vec_max)/((np.linalg.norm(vec_max) + 2.2250738585072014e-308));
    projection_mirror = np.dot(vec_centermass,vec_mirror)/((np.linalg.norm(vec_mirror) + 2.2250738585072014e-308));
    
    projection_max_v = normalize(vec_max.reshape(1,-1), axis=1).ravel() * projection_max
    projection_mirror_v = normalize(vec_mirror.reshape(1,-1), axis=1).ravel() * projection_mirror
    
    #%%
    if (projection_max >= projection_mirror):
        angulodominante = indice #180*indice/(np.pi);
    else:
        angulodominante = indice2 #180*indice2/(np.pi);
        

#    if (np.linalg.norm(projection_max_v) > np.linalg.norm(projection_mirror_v)):
#        
#        angulodominante = indice
#    else:
#        angulodominante = indice2

#    angulodominante = indice

    if debug:

        vec_max = normalize(vec_max.reshape(1,-1), axis=1).ravel()
        vec_mirror = normalize(vec_mirror.reshape(1,-1), axis=1).ravel()
        
        angulos =np.linspace(0,359,360) 
        angulos = (angulos/360) * (2 * np.pi)
        polar_graph(angulos,rho.T)
        polar_graph(angulos,mRHO.T)
        
        
        plt.plot(mRHO.T)
        plt.show()
        
        print(projection_max,projection_mirror)
        print(np.linalg.norm(projection_max_v) , np.linalg.norm(projection_mirror_v))
        print(indice,indice2)
        print(angulodominante)
        
        plt.grid(True)
        plt.xscale('linear')
        plt.yscale("linear")
        plt.yticks(np.linspace(-1000,2500,8))
        plt.xticks( np.linspace(-500,1500,5))
        plt.plot(0,0,"co")
        plt.plot(vec_max[0],vec_max[1],"bo")
        plt.plot(projection_max_v[0],projection_max_v[1],"b+")
        
        plt.plot([0,vec_max[0]],[0,vec_max[1]],"b")
        plt.plot([0,projection_max_v[0]],[0,projection_max_v[1]],"b")
        
        plt.plot(vec_mirror[0],vec_mirror[1],"ro")
        plt.plot(projection_mirror_v[0],projection_mirror_v[1],"rx")
        
        plt.plot([0,vec_mirror[0]],[0,vec_mirror[1]],"r")
        plt.plot([0,projection_mirror_v[0]],[0,projection_mirror_v[1]],"r")
        
        
        plt.plot(vec_centermass[0],vec_centermass[1],"go")

        plt.plot(vec_centermass[0],vec_centermass[1],"g")
        plt.axis('equal')
        plt.show()
        
        
        
    

    return angulodominante