Пример #1
0
def Learing(E, I1, K1, K2, Q): # define a function to learn the value of w
    #m = [K1, K2, I1]
    w = [0, 0, 0]
    # a = []
    # e = []
    apha = 0.00001
    #epoch = 1
    W = 400
    H = 300
    ans = np.zeros(H*W)
    #y = 0
    #while (epoch==1 or epoch<(W*H) and np.abs(w[y]-w[y-1])>0):
    for x in range(W*H):
        a = w[0]*K1[x] + w[1]*K2[x] + w[2]*I1[x]
        e = E[x] - a
        w[0] = w[0] + apha * e * K1[x]
        w[1] = w[1] + apha * e * K2[x]
        w[2] = w[2] + apha * e * I1[x]
    #epoch += 1
    #y += 1

    for x in range(W*H):
        ans[x] = (Q[x] - K1[x]*w[0] - K2[x]*w[1]) / w[2]
    #print ans
    ans = ans.reshape((300, 400))
    print ans

    Final_img = Image.fromarray(ans)
    Image._show(Final_img)
    Final_img.save('Final_img.jpg')
    return w
Пример #2
0
def login(username, password):
    url = 'http://i.mooc.chaoxing.com/space/index?'
    browser.get(url)
    browser.find_element_by_id('unameId').send_keys(username)
    browser.find_element_by_id('passwordId').send_keys(password)
    location = browser.find_element_by_id('numVerCode').location
    screenImg = "code.png"
    browser.get_screenshot_as_file(screenImg)
    # size=browser.find_element_by_id('numVerCode').size
    # # #browser.maximize_window()
    # # top = location['y']+90
    # # bottom = location['y'] + size['height']+95
    # # left=location['x']+140
    # # right = location['x'] + size['width']+190
    #
    # #小窗口
    # top = location['y']+90
    # bottom = location['y'] + size['height']+95
    # left=location['x']+90
    # right = location['x'] + size['width']+110
    # img = Image.open(screenImg).crop((left, top, right, bottom))
    # # img = img.convert('RGBA')  # 转换模式:L | RGB
    # # img = img.convert('L')  # 转换模式:L | RGB
    # # img = ImageEnhance.Contrast(img)  # 增强对比度
    # # img = img.enhance(2.0)  # 增加饱和度
    # img.save(screenImg)
    # img.show()
    x = Image.open('code.png')
    Image._show(x)
    code = input('请输入验证码:')
    browser.find_element_by_id('numcode').send_keys(code)
    browser.find_element_by_css_selector('.zl_btn_right').click()
    print('登陆成功')
Пример #3
0
def run():
    last = [[]]
    curr = ca_matrix
    while True:
        if np.all(last == curr):
            break
        last = np.copy(curr)
        for i in range(msize):
            for j in range(msize):
                judge_cell_state(i, j)

        curr = np.copy(ca_matrix)
        print(ca_matrix)
        print('---------------------')

    # 绘制图片
    for i in range(msize):
        for j in range(msize):
            if curr[i][j]:
                curr[i][j] = 0
            else:
                curr[i][j] = 255

    image = Image.fromarray(curr)
    Image._show(image)

    print('over')
def reverse_distort():
    m_r, m_g, m_b = create_distortion_maps()
    newImage: Image.Image = Image.new('RGB', (aImage.width, aImage.height))
    draw: ImageDraw.ImageDraw = ImageDraw.Draw(newImage)
    new_pixels = {}
    for distorted, undistorted in m_r.items():
        pixel = pixels[distorted[1]][distorted[0]]
        if undistorted not in new_pixels:
            new_pixels[undistorted] = [pixel[0],0,0]
        else:
            new_pixels[undistorted][0] = pixel[0]
    for distorted, undistorted in m_g.items():
        pixel = pixels[distorted[1]][distorted[0]]
        if undistorted not in new_pixels:
            new_pixels[undistorted] = [0, pixel[1], 0]
        else:
            new_pixels[undistorted][1] = pixel[1]
    for distorted, undistorted in m_b.items():
        pixel = pixels[distorted[1]][distorted[0]]
        if undistorted not in new_pixels:
            new_pixels[undistorted] = [0, 0, pixel[2]]
        else:
            new_pixels[undistorted][2] = pixel[2]

    for undistorted, rgb in new_pixels.items():
        draw.point((undistorted[0], undistorted[1]), fill=tuple(rgb))
    Image._show(newImage)
Пример #5
0
def make_ticket(fio, from_, to, date):
    fio = fio
    flight_from = from_
    flight_to = to
    flight_date = date
    filename = r'images/ticket_template.png'
    #lesson_path = r'python_base/lesson_013'
    path_to_file = os.path.join(os.getcwd(), filename)
    picture = Image.open(path_to_file)
    draw = ImageDraw.Draw(picture)
    font = ImageFont.truetype('arial.ttf', 15)
    draw.text((40, 120), fio, fill=ImageColor.colormap['black'], font=font)
    draw.text((40, 190),
              flight_from,
              fill=ImageColor.colormap['black'],
              font=font)
    draw.text((40, 260),
              flight_to,
              fill=ImageColor.colormap['black'],
              font=font)
    draw.text((280, 260),
              flight_date,
              fill=ImageColor.colormap['black'],
              font=font)
    Image._show(picture)
    pass
Пример #6
0
def profpic(u_name):
    try:
        api.searchUsername(u_name)
        user = api.LastJson['user']

        item = user['hd_profile_pic_versions']
        for eachit in item:
            print(str(eachit['height']) + " x " + str(eachit['width']))
            print(eachit['url'])
            print(
                str(user['hd_profile_pic_url_info']['height']) + " x " +
                str(user['hd_profile_pic_url_info']['width']))
            url_ = user['hd_profile_pic_url_info']['url']
            print(url_)

        Picture_request = requests.get(url_)
        home = str(Path.home())
        path_i = home + "\\Desktop\\temp.jpg"

        if Picture_request.status_code == 200:
            with open(path_i, 'wb') as f:
                f.write(Picture_request.content)
            hd_image = Image.open(path_i)
            Image._show(hd_image)

    except Exception as e:
        print("try again")
        print(str(e))
Пример #7
0
def test():
    filename_queue = tf.train.string_input_producer(['Climatic.png'])  # list of files to read

    reader = tf.WholeFileReader()
    key, value = reader.read(filename_queue)

    my_img = tf.image.decode_png(value)  # use png or jpg decoder based on your files.

    init_op = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init_op)

    # Start populating the filename queue.

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord, sess=sess)

    for i in range(1):  # length of your filename list
        image = my_img.eval(session=sess)  # here is your image Tensor :)

    print(image.shape)
    Image._show(Image.fromarray(np.asarray(image)))

    coord.request_stop()
    coord.join(threads)
Пример #8
0
    def make_file_pipeline(self, image_files, label_files, batch_size=None, im_width=100, im_height=100, shuffle=True,
                           sess=None):
        if batch_size == None:
            batch_size = self.batch_size

        # with open(image_files[0], "rb") as f:
        #    lines = f.readlines()
        #    print(lines)

        # image_files_prod = tf.train.string_input_producer(["S:\\Users\\Nibiru\\Source\\PyCharm-Projects\\Neural-Network-v2\\data\\train\\101_blur.jpg"], shuffle=shuffle, seed=1)
        # label_files_prod = tf.train.string_input_producer(["S:\\Users\\Nibiru\\Source\\PyCharm-Projects\\Neural-Network-v2\\data\\train\\101.jpg"], shuffle=shuffle, seed=1)
        image_files_prod = tf.train.string_input_producer(image_files, shuffle=shuffle, seed=1)
        label_files_prod = tf.train.string_input_producer(label_files, shuffle=shuffle, seed=1)

        reader = tf.WholeFileReader()

        image_file, image = reader.read(image_files_prod)
        label_file, label = reader.read(label_files_prod)

        decoded = tf.image.decode_jpeg(image, channels=3)
        decoded_label = tf.image.decode_jpeg(label, channels=3)

        image = decoded.eval(session=sess)  # here is your image Tensor :)
        print(image.shape)
        Image._show(Image.fromarray(np.asarray(image)))

        # image = tf.to_float() / 256.0
        # label = tf.to_float()/ 256.0

        image = tf.reshape(image, [im_width, im_height, 3])
        label = tf.reshape(label, [im_width, im_height, 3])

        image_batch, label_batch = tf.train.batch([image, label], batch_size=batch_size, capacity=1000)

        return image_batch, label_batch
Пример #9
0
    def ShowImage(self,img,imagename,imagechannel=1):
     #   if len(img)==0:
      #      return 1;           #1---无图像
        #数据是图像
        ty=type(img);
        if  str(ty).__contains__("PIL"):
            Image._show(img);
            return  1;
        else:
        #---数据是数组
            try:
                channel=img.shape;
                if len(channel)==2:
                    #----此时表示需要显示一个二维数组(矩形为图片)
                    plt.imshow(img,'gray');
                    plt.axis('off');
                    plt.title(imagename);
                    plt.show();
                    return 0;
                elif len(channel)==3:
                    # ----此时表示需要显示一个二维数组(矩形为图片)
                    plt.imshow(img);
                    plt.axis('off');
                    plt.title(imagename);
                    plt.show();
                    return 0;
                elif len(channel)==4:
                    #----此时表示是显示一个图像集合
                    if channel[0]>100:return 2;     #图像过多,则不显示

                    show_width_num, show_height_num = self.__caculate_factor(channel[0]);  # ----获取最优显示布局
                    plt.figure(imagename);
                    if imagechannel==1:
                        for index in range(channel[0]):
                            image_x=img[index, :, :, 0];    #对于单通的图像就这么显示
                           # image_x = img[index, :, :, :];

                            # ---------------in order to show the image ,do some ops
                           # pinjie = np.zeros([image_x.shape[0], image_x.shape[1], 2]);
                           # image = np.concatenate((image_x, pinjie), axis=2);

                            plt.subplot(show_width_num, show_height_num, index + 1);
                            #   plt.title("predict:" + str(predict[index]) + "; actual:" + str(actual[index]));
                            plt.imshow(image_x,cmap=plt.cm.gray), plt.axis('off');  # 显示图片
                          #  plt.imshow(image_x,cmap='gray'), plt.axis('off');  # 显示图片
                        plt.show();
                    else:
                        for index in range(channel[0]):
                            plt.subplot(show_width_num, show_height_num, index + 1);
                            #   plt.title("predict:" + str(predict[index]) + "; actual:" + str(actual[index]));
                            plt.imshow(img), plt.axis('off');  # 显示图片
                        plt.show();


                    return 0;
                else:
                    return 3;
            except:
                return 4;
    def PowerLaw(self,gama,c=1):
        saida = np.zeros([self.m,self.n])
        for i in range(self.m):
            for j in range(self.n):
                saida[i,j] = int(c*(self.matriz[i,j]**gama))

        img = Image.fromarray(saida)
        Image._show(img)
Пример #11
0
def ShowBinayImage(image: np.ndarray):
    im = Image.new("RGB", image.shape, 0)
    for i in range(len(image)):
        for j in range(len(image[i])):
            im.putpixel((j, i), (0, 0, 0) if image[i][j] > 0 else
                        (255, 255, 255))

    Image._show(im)
Пример #12
0
def main():
    # Argument Getter
    arguments = argparse.ArgumentParser(description="Street View Image Getter for some project")
    arguments.add_argument('-k', '--googleKey', required=True, help="Google API Key")
    arg = arguments.parse_args()

    image_test = get_images_from_gmaps(arg)
    Image._show(image_test)
Пример #13
0
def textToImage():
    snap = Snap().getConnection()
    userID = localFiles.getLocalUserInfo()[0]
    list = snap.getImageFile(userID)[0]

    #Displays all snaps found
    for element in list:
        img = Image.open(BytesIO(base64.b64decode(element)))
        Image._show(img)
Пример #14
0
def plot_image_big(image):
    # Ensure the pixel-values are between 0 and 255.
    image = np.clip(image, 0.0, 255.0)

    # Convert pixels to bytes.
    image = image.astype(np.uint8)

    # Convert to a PIL-image and display it.
    Image._show(PIL.Image.fromarray(image))
Пример #15
0
def implot(image):
    plt.figure(figsize=(8,8))
    image = image.numpy()
    image = np.transpose(image,(1,2,0))
    var = [0.172,0.168,0.195]
    mean = [0.718,0.734,0.675]
    image= image*var + mean
    im = Image.fromarray((image*255).astype(np.uint8))
    Image._show(im)
def main():
    img = Image.open("OriginalImage.jpg")
    imgArray = np.array(img)
    #RGB to GrayScale
    tempArray = RGBtoGray(imgArray)
    Image._show(Image.fromarray(tempArray))
    FilterAndShow(tempArray, [0, -1, 1])
    FilterAndShow(tempArray, [1, -1, 0])
    FilterAndShow(tempArray, [-0.5, 0, 0.5])
def reverse_distort2():
    newImage: Image.Image = Image.new('RGB', (aImage.width, aImage.height))
    draw: ImageDraw.ImageDraw = ImageDraw.Draw(newImage)
    for row in range(height):
        for col in range(width):
            pixel = get_distorted_pixel(col, row)
            #print(pixel)
            draw.point((col, row), fill=pixel)
    Image._show(newImage)
    newImage.save("newimage.png")
def subitracao(mat1, mat2, m, n):
    saida = np.zeros([m, n])
    print(saida.shape)
    for i in range(m):
        for j in range(n):
            if mat1[i, j] - mat2[i, j] < 0:
                saida[i, j] = 0
            else:
                saida[i, j] = mat1[i, j] - mat2[i, j]
    img = Image.fromarray(saida)
    Image._show(img)
Пример #19
0
 def getValue(self):
     #filePath,resizeFactor
     print("enter the file path")
     filePath=input("File path") 
     print("enter the resize factor")
     resizeFactor=input("resize factor") 
     self.filePath=filePath
     self.resizeFactor=resizeFactor
     print(resizeFactor)
     ap=Image(filename='/home/jerald/Pictures/one.jpg')
     ap._show()
def soma(mat1, mat2, m, n):
    saida = np.zeros([m, n])
    print(saida.shape)
    for i in range(m):
        for j in range(n):
            #saida[i,j] = (mat1[i,j]+ mat2[i,j])//2
            if mat1[i, j] + mat2[i, j] > 255:
                saida[i, j] = 255
            else:
                saida[i, j] = mat1[i, j] + mat2[i, j]
    img = Image.fromarray(saida)
    Image._show(img)
Пример #21
0
def google_map(good_hs, bad_hs):
    # show a Google map!

    colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black']

    # if isinstance(location, str):
    #     geo = google_geo(location)
    #     lat = geo['lat']
    #     lng = geo['lng']
    # else:
    #     lat = location[0]
    #     lng = location[1]

    # sort hotspots by number of birds! TODO: do this in find_good_hotspots, also sort p array
    good_hs = sorted(good_hs, key=lambda n: n['expected_n'])

    if len(good_hs) > 6:
        use_hs = good_hs[0:6]
    else:
        use_hs = good_hs

    print(len(use_hs))


    # Generate URL with markers
    base_url = 'http://maps.googleapis.com/maps/api/staticmap?&size=1000x1000&sensor=false]'

    url_param = ''
    # markers for good hotspots
    url_param = '&markers=size:mid%%7Ccolor:%s' %colors[0]
    ind = 0
    for x in use_hs:
        url_param += '&markers=size:mid%%7Ccolor:%s%%7Clabel:%i' %(colors[ind], ind+1)
        url_param += '%%7C%f,%f' %(x['lat'],x['lng'])
        ind += 1

    url_param += '&markers=size:tiny%%7Ccolor:%s' % colors[-1]
    for x in bad_hs[1:20]: #FIXME: make reasonable estimate of size
        url_param+='%%7C%f,%f' %(x['lat'],x['lng'])


    image_bytes = urllib.urlopen(base_url+url_param).read()
    image = Image.open(StringIO(image_bytes)) #StringIO makes file object out of image data


    # TODO
    # - take in lat,lng of hotspots
    # - plot hotspot markers, sorted by # expected new birds.


    Image._show(image)

    return image
    def negative(self):
        L = 255
        saida  = np.zeros([self.m , self.n])
        m1, n1 = saida.shape
        print('linhas : {} coluna: {}'.format(m1,n1))

        for i in range(self.m):
            for j in range(self.n):
                saida[i,j] = L  - self.matriz[i,j]

        img  = Image.fromarray(saida)
        Image._show(img)
Пример #23
0
def show_image_from_nmlz_data(data, color_mode):
    """
    Shows image in system compatible Image Viewer
    :param data: Image numpy array
    :param color_mode: Image color mode [F, RGB]
    :return:
    """
    if not verbose: return
    if is_rgb_color_mode(color_mode):
        ch = [data[0] * 255, data[1] * 255, data[2] * 255]
        Image._show(image_from_rgb_channels(ch[0], ch[1], ch[2]))
    else:
        Image._show(Image.fromarray(data * 255, color_mode))
Пример #24
0
def reflexao(mat, m, n, eixo):
    x = lambda x: x
    y = lambda y: y
    saida = np.zeros([m, n])
    if eixo == 1:
        x = lambda x: m - 1 - x
    else:
        y = lambda y: n - 1 - y
    for i in range(m):
        for j in range(n):
            saida[i, j] = mat[x(i), y(j)]
    img = Image.fromarray(saida)
    Image._show(img)
Пример #25
0
def ShowCoords(img_file, coord_file):
    IMG_DCT = "photos_used/"
    img = Image.open(IMG_DCT + img_file)
    draw = ImageDraw.Draw(img)
    COORDS_DCT = "coords/"
    coord_list = CreateData.LoadCoords(coord_file, COORDS_DCT)
    for c in coord_list:
        if c[2] == 1:
            x = c[0]
            y = c[1]
            draw.line([(x - 4, y - 4), (x + 4, y + 4)], fill="green", width=2)
            draw.line([(x - 4, y + 4), (x + 4, y - 4)], fill="green", width=2)
    del draw
    Image._show(img)
Пример #26
0
def compareRow(img1, img2, img3):
    results = {}

    Image._show(ImageChops.logical_xor(img1.convert("1"), img2.convert("1")))

    AB = compareImages(img1, img2)
    BC = compareImages(img2, img3)

    if 'result' in AB and 'result' in BC:
        if AB['result'] and BC['result'] == 'same':
            results.update({'result': 'same'})
        else:
            results.update({'result': 'different'})

    return results
Пример #27
0
def get_captcha(login_url):
    login_html = s.get(login_url, headers=headers).content
    # print(login_html)

    # try:
    # captcha_img_url = re.findall(
    #     r'<img style="CURSOR: pointer" onclick="exchangePic(this)" height="23" title="点击刷新" src="(.*?)" width="58" align="absMiddle" border="0">', login_html)[0]
    # print(captcha_img_url)

    image = Image.open('Image.png')
    captcha_code = pytesseract.image_to_string(image)

    Image._show(image)

    print(captcha_code)
def _show_seg_label(data_path):

    lbl = Image.open(data_path)
    lbl_category = FT.to_tensor(lbl) * 255

    if lbl_category.shape[0] == 3:
        lbl_category = lbl_category[0, :, :]  # (300, 300)
    lbl_category = lbl_category.data.numpy()
    lbl_category = lbl_category.astype('int')  # int64

    dd_cm = np.array(dd_colormap, dtype='uint8')

    lbl_RGB = dd_cm[lbl_category]

    lbl_RGB = Image.fromarray(lbl_RGB)
    Image._show(lbl_RGB)
Пример #29
0
def test_reader(recordsFile):
    image, label = recordsReader(recordsFile)
    with tf.Session() as sess:  # 开始一个会话
        init_op = tf.initialize_all_variables()
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for i in range(1):
            image, label = sess.run([image, label])  # 在会话中取出image和label
            # img = Image.fromarray(example, 'RGB')  # 如果img是RGB图像
            # img = Image.fromarray(example)
            #
            # img.save('./' + '_'+'Label_' + str(l) + '.jpg')  # 存下图片
            Image._show(Image.fromarray(image))
        coord.request_stop()
        coord.join(threads)
Пример #30
0
def open_image_as_array(path, open_mode, color_mode):
    """
    :param path: Path to image on disc
    :param open_mode: Mode to open image
    :param color_mode: Image color mode
    :return: Return image as numpy array object
    """
    image = adapt_img_size(Image.open(path, open_mode).convert(color_mode))
    if verbose:
        Image._show(image)
    if is_rgb_color_mode(color_mode):
        image_ch = np.array(get_channels(image))
    else:
        image_ch = np.array(image)
    image.close
    return image_ch
Пример #31
0
def show_image(identifier, images_root = definitions.TRAIN_IMAGES):
    '''
    shows the image associated with the identifier. This is the image that was rendered 
    from the structured representation with that identifier.
    As there are are 6 permutations for each such structured_representation,
    this methods shows the image where the prder of boxes fits their order in the structured representation.
    
    :param identifier: a unique identifier of the form {sentence_id}-{img id}. 
    for example '150-2'
    :param images_root: train/dev/test 
    
    '''
    im_path = __image_for_id(identifier, images_root)
    img = Image.open(im_path)
    Image._show(img)
    return
Пример #32
0
def evaluate(model, data_loader, device, file_names):
    n_threads = torch.get_num_threads()
    # FIXME remove this and make paste_masks_in_image run on the GPU
    torch.set_num_threads(1)
    cpu_device = torch.device("cpu")
    model.eval()

    coco = get_coco_api_from_dataset(data_loader.dataset)
    iou_types = _get_iou_types(model)
    coco_evaluator = CocoEvaluator(coco, iou_types)

    metric_logger = utils.MetricLogger(delimiter="  ")
    header = 'Test:'

    for (image, labels, masks) in metric_logger.log_every(data_loader, 100, header):
        image = list(img.to(device) for img in image)
        targets = list({k: v.to(device, dtype=torch.long) for k,v in t.items()} for t in labels)

        torch.cuda.synchronize()
        model_time = time.time()
        outputs = model(image)
        outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]
        model_time = time.time() - model_time

        ids = [targets[i]['image_id'].numpy() for i in range(len(targets))]
        res = {target["image_id"].item(): output for target, output in zip(targets, outputs)}
        evaluator_time = time.time()
        coco_evaluator.update(res)
        evaluator_time = time.time() - evaluator_time
        metric_logger.update(model_time=model_time, evaluator_time=evaluator_time)
        boxes = outputs[0]['boxes'].numpy()
        bmask1 = get_bbox_mask(mask=masks[0], bbox=boxes)
        Image._show(Image.fromarray(bmask1))
        dfs = 2

    # gather the stats from all processes
    metric_logger.synchronize_between_processes()
    print("Averaged stats:", metric_logger)
    coco_evaluator.synchronize_between_processes()

    # accumulate predictions from all images
    coco_evaluator.accumulate()
    coco_evaluator.summarize()
    torch.set_num_threads(n_threads)
    return coco_evaluator
Пример #33
0
def wrapper_acgpn():
    for filename in os.listdir('../Data_preprocessing/test_label'):
        if filename != variableModels.get()[:8] + '.png':
            os.remove(filename[:8] + '.png')

    if len(os.listdir('../Data_preprocessing/test_label')) == 0:
        copyfile('./pictures/Label/' + variableModels.get()[:8] + '.png',
                 '../Data_preprocessing/test_label/' + variableModels.get()[:8] + '.png')

    copyfile('./pictures/Models/' + variableModels.get(), '../Data_preprocessing/test_img/' + variableModels.get())
    copyfile('./pictures/dresses/' + variableDresses.get(), '../Data_preprocessing/test_color/' + variableDresses.get())

    launch_acgpn()

    preproc_img = Image.open('./sample/' + variableModels.get())
    w, h = preproc_img.size

    Image._show(preproc_img.crop((384, 0, w, h)))
Пример #34
0
def decode(image_ch, color_mode="F", mode="D2"):
    """
    :param image_ch: Numpy array of encoded image channel(s)
    :param color_mode: Image color mode [F, RGB]
    :param mode: Mode of transformation [D2, D4]
    :return: Decoded image object
    """
    if verbose:
        print("DECODING ...\n",
              "\nColor mode: " + color_mode,
              "\nTransformation mode: " + mode)
    CL = check_mode(mode)
    if is_rgb_color_mode(color_mode):
        decoded_img = decode_rgb(image_ch, CL)
    else:
        decoded_img = decode_grayscale(image_ch, CL)
    if verbose:
        Image._show(decoded_img)
    return decoded_img
Пример #35
0
import mahotas
import numpy    
import pylab
import scipy
from PIL import Image,ImageDraw
from Tkinter import *
from tkFileDialog import askopenfilename
from PIL import Image, Image



print "Reading image to im"
im = Image.open("track.png")
im = im.resize((900,600),Image.ANTIALIAS);

Image._show(im)

px = [] 
py = [] 

def onmouse(event):
    px.append(event.x)
    py.append(event.y)
    return px,py





#===============================================================================
# print 'Reading image from file'
Пример #36
0
def google_map(good_hotspots):
    # show a Google map of hotspots ranked by goodness!

    # sort hotspots by expected number of birds!
    hs_sort = sorted(good_hotspots, key=lambda x: x['expected_n'], reverse=True)

    expected_n = [x['expected_n'] for x in good_hotspots]
    cutoff = max(expected_n) - (max(expected_n) - min(expected_n))*0.5

    use_good = []
    use_bad = []
    for x in hs_sort[:20]:
        if x['expected_n'] >= cutoff:
            use_good.append(x)
        else:
            use_bad.append(x)

    good_marker_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
    while len(good_marker_colors) < len(use_good):
        good_marker_colors.extend(good_marker_colors)
    bad_marker_colors = ['black']

    # Print to screen
    print '\nTop hotspots:'
    for idx_good, hs in enumerate(use_good):
        print '%i: %s , expected number of new birds = %.2f' \
              % (idx_good+1, hs['locality'], hs['expected_n'])
    print '\nAdditional hotspots:'
    for hs in use_bad:
        print '%s , expected number of new birds = %.2f' \
              % (hs['locality'], hs['expected_n'])

    # Use top 20%:
    # max_hotspots = 20
    # if len(good_hotspots) > 1:
    #     ind_cutoff = int(len(good_hotspots)*0.2)
    #     cutoff = 'Top 20%'
    # else:
    #     ind_cutoff = len(good_hotspots)
    #     cutoff = 'All good'
    #
    # print '\n%s of hotspots:' % cutoff
    # for idx, hs in enumerate(hs_sort):
    #     if idx == ind_cutoff:
    #         print '\nOthers'
    #     print '%i: %s , expected number of new birds = %.2f' % (idx+1, hs['locality'], hs['expected_n'])
    # use_good = hs_sort[:ind_cutoff]
    # use_bad = hs_sort[ind_cutoff:]

    # Generate URL with markers
    base_url = 'http://maps.googleapis.com/maps/api/staticmap?&size=1000x1000&sensor=false]'

    url_param = ''
    # markers for good hotspots
    url_param = '&markers=size:mid%%7Ccolor:%s' %good_marker_colors[0]
    for idx_good, x in enumerate(use_good):
        url_param += '&markers=size:mid%%7Ccolor:%s%%7Clabel:%i' \
                     % (good_marker_colors[idx_good], idx_good+1)
        url_param += '%%7C%f,%f' %(x['lat'], x['lng'])

    # markers for bad hotspots
    url_param += '&markers=size:mid%%7Ccolor:%s' % bad_marker_colors[0]
    for idx_bad, x in enumerate(use_bad):
        url_param += '&markers=size:small%%7Ccolor:%s%%7Clabel:%i' \
                     % (bad_marker_colors[0], idx_bad + idx_good +2)
        url_param += '%%7C%f,%f' %(x['lat'], x['lng'])

    image_bytes = urllib.urlopen(base_url+url_param).read()
    image = Image.open(StringIO(image_bytes))  # StringIO makes file object out of image data

    Image._show(image)

    return
Пример #37
0
def read_images(path, is_directory=True):

  images = []
  png_files = []
  jpeg_files = []

  reader = tf.WholeFileReader()

  png_files_path = glob.glob(os.path.join(path, '*.[pP][nN][gG]'))
  jpeg_files_path = glob.glob(os.path.join(path, '*.[jJ][pP][eE][gG]')) #,
  jpg_files_path = glob.glob(os.path.join(path, '*.[jJ][pP][gG]')) # glob.glob(os.path.join(path + '*.[jJ][pP][nN][gG]'))

  print(png_files_path)
  # jpeg_files_path = [glob.glob(path + '*.jpg'), glob.glob(path + '*.jpeg')]

  if is_directory:
    for filename in png_files_path:
      png_files.append(filename)
    for filename in jpeg_files_path:
      jpeg_files.append(filename)
    for filename in jpg_files_path:
      jpeg_files.append(filename)
  else:
     _, extension = os.path.splitext(path)
     print(extension)
     if extension.lower() == '.png':
      key, value = reader.read(tf.train.string_input_producer(path))
      img = tf.image.decode_png(value)
      print(img)
      Image._show(Image.fromarray(np.asarray(img)))
      return img


  # Decode if there is a PNG file:
  if len(png_files) > 0:
    png_file_queue = tf.train.string_input_producer(png_files)
    pkey, pvalue = reader.read(png_file_queue)
    p_img = tf.image.decode_png(pvalue)

  if len(jpeg_files) > 0:
    jpeg_file_queue = tf.train.string_input_producer(jpeg_files)
    jkey, jvalue = reader.read(jpeg_file_queue)
    j_img = tf.image.decode_jpeg(jvalue)


  with tf.Session() as sess:

    # Start populating the filename queue.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    if len(png_files) > 0:
      for i in range(len(png_files)):
        png = p_img.eval()
        images.append(png)

      # Image._showxv(Image.fromarray(np.asarray(png)))

    if len(jpeg_files) > 0:
      for i in range(len(jpeg_files)):
        jpeg = j_img.eval()
        images.append(jpeg)

    coord.request_stop()
    coord.join(threads)

  return images