示例#1
0
def compute_stippling(path):
    features_path = path.replace("/pre_processed/", "/features/")
    features_path = os.path.splitext(features_path)[0] + ".npz"
    image = Image(path)
    image = image.resize(200, 200)
    image.convert_to_gray()

    # Compute stippled image and plot it.
    stippling = Stippling(image, 10000, 15, 2)
    stippling.generate()
    stippling.save(features_path)
    # stippling.plot()
    print features_path
示例#2
0
def combine_images(image1, image2):
    # let's combine two images using the squared sum of squares: value = sqrt(value_1**2, value_2**2)
    # size of image1 and image2 MUST be the same
    x_pixels, y_pixels, num_channels = image1.array.shape  # represents x, y pixels of image, # channels (R, G, B)
    new_im = Image(
        x_pixels=x_pixels, y_pixels=y_pixels,
        num_channels=num_channels)  # making a new array to copy values to!
    for x in range(x_pixels):
        for y in range(y_pixels):
            for c in range(num_channels):
                new_im.array[x, y, c] = (image1.array[x, y, c]**2 +
                                         image2.array[x, y, c]**2)**0.5
    return new_im
示例#3
0
def combine_vertical_images(stack):
    combined_slide = []
    if len(stack) % 2 == 0:
        while len(stack) > 0:
            image1 = stack.pop()
            image2 = stack.pop()
            combine_tags = image1.tags | image2.tags
            combined_image = Image('H', len(combine_tags), combine_tags)
            combined_slide.append(combined_image)
    else:
        print("Error")
    combined_slide.reverse()
    return combined_slide
示例#4
0
 def getImage(projectId, imageId):
     image = Image(imageId)
     connection = lite.connect(DATABASE_NAME)
     with connection:
         cur = connection.cursor()
         cmd = DB.QueryImage
         cmd += "WHERE ProjectId=? AND ImageId=?"
         vals = (projectId, imageId)
         cur.execute(cmd, vals)
         results = cur.fetchall()
         if len(results) > 0:
             image = DB.toImage(results[0])
     return image
示例#5
0
def brighten(image, factor):
    # when we brighten, we just want to make each channel higher by some amount
    # factor is a value > 0, how much you want to brighten the image by (< 1 = darken, > 1 = brighten)
    x_pixels, y_pixels, num_channels = image.array.shape  # represents x, y pixels of image, # channels (R, G, B)
    # make new image to prevent change to the previous one
    new_im = Image(
        x_pixels=x_pixels, y_pixels=y_pixels,
        num_channels=num_channels)  # making a new array to copy values to!

    # vectorized version using numpy
    new_im.array = image.array * factor

    return new_im
示例#6
0
    def main():
        app_cfg = AppConfig()

        LOGGER.info('Input csv path:{}'.format(app_cfg.input))

        LOGGER.info('Output csv path:{}'.format(app_cfg.output))
        LOGGER.info('Image whitelist:{}'.format(app_cfg.image_whitelist))

        csv_input = CsvConfig(app_cfg)
        csv_input.validate()
        csv_input.report('w', 'image1', 'image2', 'similarity', 'elapsed')

        for line in csv_input.contents:
            start_time = int(round(time.time() * 1000))
            image1 = Image(line[0])
            image2 = Image(line[1])
            (score, diff) = compare_ssim(image1.grayscale, image2.grayscale, full=True)
            bjorn_score = round(score.item(), 3)
            if bjorn_score > 0.99:
                bjorn_score = 0
            time_diff = int(round(time.time() * 1000)) - start_time
            csv_input.report('a', image1.path, image2.path, bjorn_score, time_diff)
示例#7
0
 def hit_limit(self, device):
     """check whether hit the limit of inventory"""
     limit_warning = Image(constant.HIT_LIMIT_ICON)
     check_result = limit_warning.exists(device)
     if check_result:
         if not self.power_up_system.already_power_up:
             self.power_up_system.run(device)
         else:
             self.retire_system.run(device)
             self.power_up_system.already_power_up = False
         return True
     else:
         return False
示例#8
0
def change_brightness(image, factor):
    # factor is a value  (0 < n > 1) to determine the brightness
    # (< 1 = darken, < 1 = brighten)
    x_pixels, y_pixels, num_channels = image.array.shape  # get dimension(x,y), channels
    # * make an empty image so that we don't modify the original
    new_image = Image(x_pixels, y_pixels, num_channels)

    for x in range(x_pixels):
        for y in range(y_pixels):
            for c in range(num_channels):
                new_image.array[x, y, c] = image.array[x, y, c] * factor

    return new_image
示例#9
0
def compose(channels):
    # 'channels' is a sequence of Images.
    outch = []
    i = 0
    for c in channels:
        if c.components == 1:
            outch.append(c.data[:, :, 0:1])
        else:
            if c.components < i:
                raise TypeError("Image No. %i has not enough channels" % i)
            outch.append(c.data[:, :, i:i + 1])
        i += 1
    return Image(data=numpy.dstack(outch).astype(numpy.uint8))
示例#10
0
def adjust_contrast(image, factor, mid=0.5):
    # adjust the contrast by increasing the difference from the user-defined 
    # midpoint by factor amount
    x_pixels, y_pixels, num_channels = image.array.shape
    new_im = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels)

    for x in range(x_pixels):
        for y in range(y_pixels):
            for c in range(num_channels):
                new_im.array[x, y, c] = (image.array[x, y, c ] - mid) * factor + mid

    new_im.array = (image.array - mid) * factor + mid
    return new_im
示例#11
0
def adjust_contrast(image, factor, mid):
    # adjust the contrast by increasing the difference from the user-defined midpoint by factor amount
    x_pixels, y_pixels, num_channels = image.array.shape  # represents x, y pixels of image, # channels (R, G, B)
    new_im = Image(
        x_pixels=x_pixels, y_pixels=y_pixels,
        num_channels=num_channels)  # making a new array to copy values to!
    for x in range(x_pixels):
        for y in range(y_pixels):
            for c in range(num_channels):
                new_im.array[x, y,
                             c] = (image.array[x, y, c] - mid) * factor + mid

    return new_im
示例#12
0
 def test_022(self):
     """ config - RGB to grayscale """
     image = Image("tests/0_100.jpg", config=['gray'])
     self.assertEqual(image.image, "tests/0_100.jpg")
     self.assertEqual(image.name, "0_100")
     self.assertEqual(image.type, "jpg")
     self.assertEqual(image.dir, "./")
     self.assertEqual(image.size, 3643)
     self.assertEqual(image.shape, (100, 100))
     self.assertEqual(image.classification, 0)
     self.assertTrue(os.path.isfile("0_100.h5"))
     os.remove("0_100.h5")
     image = Image("tests/0_100.jpg", config=['grayscale'])
     self.assertEqual(image.image, "tests/0_100.jpg")
     self.assertEqual(image.name, "0_100")
     self.assertEqual(image.type, "jpg")
     self.assertEqual(image.dir, "./")
     self.assertEqual(image.size, 3643)
     self.assertEqual(image.shape, (100, 100))
     self.assertEqual(image.classification, 0)
     self.assertTrue(os.path.isfile("0_100.h5"))
     os.remove("0_100.h5")
示例#13
0
def boot_image(manifest, build_server, bootstrap_info):
	image_id = None
	try:
		import os
		from bootstrapvz.common.tools import log_check_call
		docker_machine = build_server.run_settings.get('docker', {}).get('machine', None)
		docker_env = os.environ.copy()
		if docker_machine is not None:
			cmd = ('eval "$(docker-machine env {machine})" && '
			       'echo $DOCKER_HOST && echo $DOCKER_CERT_PATH && echo $DOCKER_TLS_VERIFY'
			       .format(machine=docker_machine))
			[docker_host, docker_cert_path, docker_tls] = log_check_call([cmd], shell=True)
			docker_env['DOCKER_TLS_VERIFY'] = docker_tls
			docker_env['DOCKER_HOST'] = docker_host
			docker_env['DOCKER_CERT_PATH'] = docker_cert_path
			docker_env['DOCKER_MACHINE_NAME'] = docker_machine
		from bootstrapvz.remote.build_servers.local import LocalBuildServer
		image_id = bootstrap_info._docker['image_id']
		if not isinstance(build_server, LocalBuildServer):
			import tempfile
			handle, image_path = tempfile.mkstemp()
			os.close(handle)
			remote_image_path = os.path.join('/tmp', image_id)
			try:
				log.debug('Saving remote image to file')
				build_server.remote_command([
					'sudo', 'docker', 'save',
					'--output=' + remote_image_path,
					image_id,
				])
				log.debug('Downloading remote image')
				build_server.download(remote_image_path, image_path)
				log.debug('Importing image')
				log_check_call(['docker', 'load', '--input=' + image_path], env=docker_env)
			except (Exception, KeyboardInterrupt):
				raise
			finally:
				log.debug('Deleting exported image from build server and locally')
				build_server.delete(remote_image_path)
				os.remove(image_path)
				log.debug('Deleting image from build server')
				build_server.remote_command(['sudo', 'docker', 'rmi',
				                             bootstrap_info._docker['image_id']])

		from image import Image
		with Image(image_id, docker_env) as container:
			yield container
	finally:
		if image_id is not None:
			log.debug('Deleting image')
			log_check_call(['docker', 'rmi', image_id], env=docker_env)
示例#14
0
    def __init__(self,
                 image,
                 trace=False,
                 syms=False,
                 timeout=None,
                 preformatted_image=os.path.join('..', 'floppy.img.zip'),
                 argv=None,
                 keep_temps=False,
                 qemu_opts=[]):
        self.image = image
        self.trace = trace
        self.syms = syms
        self.timeout = timeout
        self.argv = argv
        self.keep_temps = keep_temps
        self.qemu_opts = qemu_opts

        assert os.path.exists(self.image)

        with open(self.image, 'rb') as fd:
            elffile = ELFFile(fd)
            if elffile.get_machine_arch() == 'x86':
                self.arch = 'X86'
            else:
                raise RuntimeError("Unknown architecture: %s" %
                                   elf.get_machine_arch())

            if syms:
                # Get the symbols in the file.
                self.symbols = {}
                for section in elffile.iter_sections():
                    if not isinstance(section, SymbolTableSection):
                        continue

                    for sym in section.iter_symbols():
                        self.symbols[sym['st_value']] = sym.name

        if self.arch == 'X86':
            if os.environ.get('MODEL', '').lower() == 'bochs':
                self.model = Bochs('bochs', [])
            else:
                self.model = Qemu('qemu-system-i386', self.qemu_opts)

        else:
            raise RuntimeError("Unknown architecture: %s" % self.arch)

        fd, self.tmpimage = tempfile.mkstemp()
        os.close(fd)
        self.floppy_image = Image(self.tmpimage, preformatted_image)
        self.floppy_image.create_grub_conf(args=self.argv)
        self.floppy_image.copy(self.image, '/kernel')
示例#15
0
def main():

    # setting
    width = 320
    height = 200
    ar = width / height
    grey = Color(0.1, 0.1, 0.1)
    red = Color(1, 0, 0)

    # setup objects
    camera = Vector(0, 0, -1)
    sphere = Sphere(0, 0, 0, 0.5)

    # setup image
    im = Image(width, height)

    ###
    xmin = -1
    xmax = 1
    ymax = xmax / ar
    ymin = -ymax
    dx = (xmax - xmin) / (width - 1)
    dy = (ymax - ymin) / (height - 1)
    print("x:[{}, {}] y:[{}, {}]".format(xmin, xmax, ymin, ymax))
    z = 0
    for j in range(height):
        y = ymin + dy * j
        for i in range(width):
            x = xmin + dx * i
            end = Vector(x, y, z)
            U = end - camera  # unit vector from camera to end point
            u = U.normalize()

            # calculate discriminant
            sphere2ray = sphere - camera
            a = 1
            b = 2 * u.dot(sphere2ray)
            c = sphere2ray.magnitude() - sphere.r * sphere.r
            delta = b * b - 4 * a * c
            if delta < 0:
                c = grey
            else:
                c = red
            im.set_pixel(j, i, c)

    # iterate over pixels
    # check sphere-line interesection
    # give a color
    # im.set_pixel(j, i, color)

    im.export('sphere.ppm')
示例#16
0
def parse(file):
    img = Image(file)

    cur_pos = find_cur_pos(img)
    assert (cur_pos != None)

    next_pos = find_next_pos(img, cur_pos)
    assert (next_pos != None)

    img.line(cur_pos, next_pos)
    jump(img.width, img.height, cur_pos, next_pos)

    img.save()
    img.close()
示例#17
0
def calculate_distances(input_data, desc='SIFT'):
    desc_len = 64  # SURF descriptor length
    if desc == 'SIFT':
        desc_len = 128
    X_desc = []
    temp = []
    for x in input_data.iloc[:, 0]:
        print(x)
        image = Image(x).image_read(resize=False)
        img = np.float64(image) / np.max(image)
        img = img.astype('float32')
        temp.append(img)
        _, _, fd = Descriptor(desc, image).algorithm(desc)
        X_desc = np.append(X_desc, None)  # Allocate space for your new array
        X_desc[-1] = fd

    dist = []
    print('len(X_desc)', len(X_desc))
    for i in range(0, len(X_desc)):
        for j in range(i + 1, len(X_desc)):
            sim = -1
            if ((X_desc[i] is not None) and (X_desc[j] is not None)):
                sim = BFMatcher().match_images(desc_a=X_desc[i],
                                               desc_b=X_desc[j])
            dist.append(sim)

    for i in range(0, len(X_desc)):
        if X_desc[i] is None:
            X_desc[i] = np.zeros((2, 3), dtype=float)
    print('max(X) = ', max(dist))
    max_value = max(dist)
    dist_desc = [x if x >= 0 else max_value for x in dist]

    ####################################################
    X_I = np.zeros(
        [len(X_desc),
         len(max(X_desc, key=lambda x: len(x))), desc_len])

    for i, j in enumerate(X_desc):
        for k, l in enumerate(j):
            X_I[i][k][0:len(l)] = l
        print(i, len(j), X_I[i][0:len(j)], j, end='  ')

    x_size = len(input_data)
    X_I = X_I.reshape(x_size, -1).astype('float32')
    print('X_I.shape  ', X_I.shape)

    ####################################################

    return X_I, dist_desc
示例#18
0
    def median_reduction(self, kernel_size):
        if (kernel_size <= 0):
            raise KernelError("The kernel must be greater than zero")
        elif (kernel_size % 2 == 0):
            raise KernelError("The kernel given must be of odd parity")

        bf = self.image.read_bright_field()
        gfp = self.image.read_gfp()

        # now blur
        bf = cv2.medianBlur(bf, kernel_size)
        gfp = cv2.medianBlur(gfp, kernel_size)

        return Image(bf, gfp, self.image.name)
示例#19
0
def combine_images(image1, image2):
    # image1 and image2 should be the same shape
    if image1.array.shape != image2.array.shape:
        return

    x_pixels, y_pixels, num_channels = image1.array.shape
    new_img = Image(x_pixels=x_pixels, y_pixels=y_pixels, num_channels=num_channels)

    for x in range(x_pixels):
        for y in range(y_pixels):
            for c in range(num_channels):
                new_img.array[x, y, c] = (image1.array[x, y, c] ** 2 + image2.array[x, y, c] ** 2) ** 0.5

    return new_img
示例#20
0
 def find_cars(self, img, show=False, rescale=True):
     """
         Define a single function that can extract features using hog sub-sampling and make predictions
     """
     global global_i
     if global_i < 600:
         global_i += 1
         return img
     global_i += 1
     images = [Image(img, scale, self.YSTART, self.YSTOP, rescale=rescale) for scale in self.SCALES]
     img = self.detect_new_cars(img, images, show=show)
     self.first = False
     img = self.draw_boxes(img)
     return img
示例#21
0
 def receive(self):
     page = self.socket.receive()
     unpacker = xdrlib.Unpacker(page)
     self.width = unpacker.unpack_int()
     self.height = unpacker.unpack_int()
     self.frame = unpacker.unpack_int()
     self.image = Image(self.width, self.height,
                        self.frame / Image.bytes_per_pixel, unpacker)
     self.time_step = unpacker.unpack_int()
     self.time = unpacker.unpack_double()
     unpacker.unpack_int()  # throw away cycle
     self.inlets = unpacker.unpack_int()
     self.mouse_pressure = unpacker.unpack_double()
     self.mouse_stress = unpacker.unpack_double()
示例#22
0
 def __init__(self, ai_settings, screen):
     """初始化外星人并设置起始位置"""
     super(Alien, self).__init__()
     self.screen = screen
     self.ai_settings = ai_settings
     #加载外星人图像,并设置rect属性
     image = Image()
     self.image = image.getImage('alien')
     self.rect = self.image.get_rect()
     #每个外星人最初都在屏幕左上角附近
     self.rect.x = self.rect.width
     self.rect.y = self.rect.height
     #存储外星人的准确位置
     self.x = float(self.rect.x)
示例#23
0
 def test_009(self):
     """ image properties """
     image = Image("tests/0_100.jpg")
     self.assertEqual(image.image, "tests/0_100.jpg")
     self.assertEqual(image.name, "0_100")
     self.assertEqual(image.type, "jpg")
     self.assertEqual(image.dir, "./")
     self.assertEqual(image.size, 3643)
     self.assertEqual(image.shape, (100, 100, 3))
     self.assertEqual(image.classification, 0)
     self.assertTrue(len(image.raw) > 0)
     self.assertEqual(image.thumb, None)
     self.assertTrue(os.path.isfile("0_100.h5"))
     os.remove("0_100.h5")
示例#24
0
    def getMNT(self):
        """ Permet de récupérer un array Numpy du modèle numérique de terrain. Les valeurs à l'extérieur de
            l'intervalle valide sont masquées.
                Returns:
                    mnt_array (Numpy.ma.masked_array): Array des valeurs de modèle numérique de terrain (MNT).
        """
        mnt_image = Image(self.mnt)

        # 0 = niveau moyen des mers
        mnt_array = mnt_image.getArray(masked=True,
                                       lower_valid_range=-500,
                                       upper_valid_range=9000)

        return mnt_array
示例#25
0
 def generate_mosaic(self, input_base64, num_clusters, img_length,
                     tile_size, palette_name):
     """
     Generates a mosaic from  a base64 filedata string.
     """
     img = Image(img_length)
     img \
         .load_str(input_base64) \
         .apply_filter(QuantizeFilter(num_clusters)) \
         .apply_filter(ConstrainPaletteFilter(self.color_generator, palette_name)) \
         .apply_filter(BuildMapFilter(tile_size))
     output_base64 = img.dump_str_base64('png')
     print 'image generated..'
     return output_base64
示例#26
0
 def execute(self):
     try:
         if self.feed_amount > 0:
             self.servo_man.run()
         image_file_names = self.camera_man.take_picture_series(3)
         self.clear_images()
         for image_file_name in image_file_names:
             image = Image()
             image.file_name = image_file_name
             self.add_image(image)
         self.has_run = 'true'
     except:
         self.clear_images()
         self.has_run = 'false'
示例#27
0
def load_originals(originals_list, originals_path):
    """
    method loads images into Image structure
    """
    data = []
    for i, item in enumerate(originals_list):
        #load original
        original = cv2.imread(os.path.join(originals_path, item), -1)

        #load into required structure
        dato = Image(original, os.path.join(originals_path, item), False)
        data.append(dato)

    return data
示例#28
0
def getMatchedImage(inUser):
    """Get an image can match this user, keep it simple and stupid"""
    if len(LoadedImage.loadedImages) > 0:
        for img in reversed(LoadedImage.loadedImages):
            imgUser = fetchUserByID(img.authorID)
            if (inUser.openid != imgUser.openid
                ) and not (inUser.combinedHistory.get(str(img._id), None)):
                inUser.combinedHistory[str(img._id)] = 'used'
                return img
    dfImage = Image()
    dfImage.author = user('openid')
    dfImage.author.nickName = '羽毛粉丝'
    dfImage.url = 'http://www.enjoyxue.com/static/IMG_0493.JPG'
    return dfImage
示例#29
0
def seed_images():
    with open("seeds/images_seed.txt") as f:
        reader = csv.reader(f, delimiter="|")
        for row in reader:
            dish_id = row[0]
            filename = row[1].strip()

            image = Image(dish_id=dish_id, filename=filename)
            db_session.add(image)

    try:
        db_session.commit()
    except sqlalchemy.exc.IntegrityError, e:
        db_session.rollback()
示例#30
0
    def load_events_from_data(self, data):
        if data is not None:
            json_data = json.loads(data)
            for e in json_data['events']:
                event = Event()
                event.id = int(e['id'])
                event.feed_amount = int(e['feed_amount'])
                event.event_time = datetime.strptime(e['event_time'], '%Y-%m-%dT%H:%M:%S.%fZ')
                event.has_run = e['has_run']
                for i in e['images']:
                    image = Image()
                    image.file_name = i['file_name']
                    event.add_image(image)

                self.add_event(event)