Beispiel #1
0
def main():
    lines = open(sys.argv[1]).readlines()
    width = int(sys.argv[2])
    height = int(sys.argv[3])
    layers = []
    line = lines[0].rstrip('\n')
    offset = 0
    while offset < len(line):
        layerPixels = line[offset:offset+6*25]
        layers.append(layerPixels)
        offset += (height*width)

    decodedImg = ""
    for idx in range(height * width):
        i = 0
        while layers[i][idx] == '2':
            i += 1
        decodedImg += layers[i][idx]
    rgbArray = np.zeros((6,25,3), 'uint8')

    for i in range(height):
        for j in range(width):
            if decodedImg[i*width + j] == '1':
                rgbArray[i,j,0] = 0xff
                rgbArray[i,j,1] = 0xff
                rgbArray[i,j,2] = 0xff
    img = Image.fromarray(rgbArray)
    img.save('myimg.jpeg')
Beispiel #2
0
def drawfunc():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    gluLookAt(W / 2, H / 2, -1, W / 2, H / 2, 0, 0, -1, 0)
    glColor3f(1.0, 1.0, 1.0)
    '''
    glBegin(GL_POINTS)
    for i in range(ans_3d_tra.shape[1]):
        glVertex3fv(ans_3d_tra[:,i])
    glEnd()

    '''
    #print(topology.shape[0])
    for i in range(topology.shape[0]):
        glBegin(GL_POLYGON)
        index_0 = topology[i, 0] - 1
        glVertex3fv(ans_3d_tra[:, index_0])
        index_1 = topology[i, 1] - 1
        glVertex3fv(ans_3d_tra[:, index_1])
        index_2 = topology[i, 2] - 1
        glVertex3fv(ans_3d_tra[:, index_2])
        glEnd()
    '''
    glColor3f(0.0, 1.0, 0.0) 
    glBegin(GL_POINTS)
    for i in range(hair_3d_tra.shape[1]):
        glVertex3fv(hair_3d_tra[:,i])
    glEnd()
    '''
    glColor3f(0.0, 0, 1.0)

    #print(hair_cell.shape[0])
    for i in range(hair_cell.shape[0]):
        glBegin(GL_POLYGON)
        index_0 = hair_cell[i, 0]
        glVertex3fv(hair_3d_tra[:, index_0])
        index_1 = hair_cell[i, 1]
        glVertex3fv(hair_3d_tra[:, index_1])
        index_2 = hair_cell[i, 2]
        glVertex3fv(hair_3d_tra[:, index_2])
        glEnd()

    glutSwapBuffers()
    glFlush()

    x, y, width, height = glGetIntegerv(GL_VIEWPORT)
    print(x, y, width, height)
    data = glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE)
    image = Image.frombytes("RGB", (W, H), data)
    image = ImageOps.flip(image)
    image.save(path_dic_result + 'hair_without_face.png', 'PNG')
    sys.exit()

    glutPostRedisplay()
Beispiel #3
0
def textgenerator(thema, zahl, stand):
    font = ImageFont.truetype("/font/IBMPlexSans-Regular.ttf", 80)
    font2 = ImageFont.truetype("/font/IBMPlexSans-Regular.ttf", 40)
    font3 = ImageFont.truetype("/font/IBMPlexSans-Regular.ttf", 10)
    img = Image.new("RGBA", (440, 220), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    draw.text((45, 30), thema, (0, 0, 0), font=font2)
    draw.text((45, 80), str(f'{zahl:n}'), (0, 0, 0), font=font)
    draw.text((100, 190), "Datenstand: " + str(stand), (0, 0, 0), font=font3)
    draw = ImageDraw.Draw(img)
    dateiname = "wort.png"
    img.save(dateiname)
Beispiel #4
0
    def kmeanDraw(self):
        cp_imgarr = copy.deepcopy(self.px)
        img = Image.new('RGB', (self.img_width, self.img_height), "white")
        p = img.load()

        Distance = cdist(self.px, self.centroids)
        cluster_id = np.argmin(Distance, axis=1)

        for i in range(len(cluster_id)):
            RGB_value = self.centroids[cluster_id[i]] * 255
            cp_imgarr[i] = RGB_value

        i = 0
        for x in range(self.img_width):
            for y in range(self.img_height):
                p[x, y] = tuple(cp_imgarr[i].astype(int))
                i += 1
        img.show()
        img.save('Kmean' + str(self.K) + '_poblem3.jpg')
 def _add_title(self, num_extensions, in_fqn, font_size=16, offset=0):
     if (self._instrument in [md.Inst.MEGACAM, md.Inst.MEGAPRIME]
             and num_extensions < 36):
         # SF 02-26-21
         # add an option to the ds9 command: -grid title text {this file
         # has only XX HDUs}`, only for MegaPrime files below a threshold
         # of 36 extensions. I couldn't get ds9 to work, so use PIL
         # instead.
         title = f'{self._storage_name.file_name} has only ' \
                 f'{num_extensions} HDUs'
         image = Image.open(in_fqn)
         width, height = image.size
         draw = ImageDraw.Draw(image)
         font = ImageFont.truetype(
             '/usr/local/lib/python3.8/site-packages/matplotlib/mpl-data/'
             'fonts/ttf/DejaVuSans-Bold.ttf', font_size)
         text_width, text_height = draw.textsize(title, font=font)
         text_length = draw.textlength(title)
         margin = 10
         x = width / 2 - text_length / 2 - margin * offset
         y = text_height + margin
         # text is black
         draw.text((x, y), title, (0, 0, 0), font=font)
         image.save(in_fqn)
Beispiel #6
0
data = image.imread("./avaliacao_01/Andreson_oficial_1/q6.jpg")

image2 = Image.fromarray(data)
# Exibir o array de pixel como imagem
image2 = Image.fromarray(data)
# converter o array de pixel em objeto Image Pillow
pil_image = Image.fromarray(np_array)
# verificar o tipo do objeto
type(image2)
# converter um objeto do tipo imagem para um array numpy
im = PIL.Image.fromarray(numpy.uint8(I))
# Imprimir em tela os atributos do array
print(data.dtype)
print(data.shape)
# imprimir (salvar) a imagem no formato PNG
image.save("sample_data/imagens/brasilia.png", format="PNG")
# imprimir (salvar) a imagem no formato GIF
image.save("sample_data/imagens/brasilia.gif", format="GIF")
# Exibir a imagem e verificar o formato:
print(image3.format)
# Converter a imagem em escala de cinza
image_gray = image.convert(mode="L")
image_gray
# Exibir tamanho
print(image.size)
# Gerar thumbnail ignorando aspecto ratio
image_gray.thumbnail((100, 100))
# Flip da imagem (inverter)
horizontal_image = image2.transpose(Image.FLIP_LEFT_RIGHT)
# Exibir coordenadas específicas
pyplot.imshow(horizontal_image)
print(image.size)
#   # Exibir as propriedades da imagem em um array de pixel
image2 = Image.fromarray(data)
#   # Exibir o array de pixel como imagem
image2 = Image.fromarray(data)
 # converter o array de pixel em objeto Image Pillow
pil_image=Image.fromarray(np_array)
#   # verificar o tipo do objeto
type(image2)
#   # converter um objeto do tipo imagem para um array numpy
im = PIL.Image.fromarray(numpy.uint8(I))
#   # Imprimir em tela os atributos do array
print(data.dtype)
print(data.shape)
#   # imprimir (salvar) a imagem no formato PNG
image.save("CG_Processamento_Imagens\data\input\q6.jpg",format="PNG")
#   # imprimir (salvar) a imagem no formato GIF
image.save("CG_Processamento_Imagens\data\input\q6.gif",format="GIF")
#   # Exibir a imagem e verificar o formato:
print(image3.format)
#   # Converter a imagem em escala de cinza
# image_gray = image.convert(mode="L")
image_gray
#   # Exibir tamanho
print(image.size)
#   # Gerar thumbnail ignorando aspecto ratio
image_gray.thumbnail((100,100))
#   # Flip da imagem (inverter)
horizontal_image = image2.transpose(Image.FLIP_LEFT_RIGHT)
#   # Exibir coordenadas específicas
pyplot.imshow(horizontal_image)
def _download_image(file_name, url):
    try:
        img = Image.open(requests.get(url, stream=True).raw).convert('RGB')
        img.save(file_name + '.jpg', 'JPEG')
    except OSError:
        print('Erreur downloading image ', file_name)
import numpy as np
import matplotlib.image as mpimg
img = mpimg.imread("panda-corner.jpeg")
img = mpimg.imread("panda-corner.jpg")
img.size
img.shape
img
copy = img.clone()
copy = img.copy()
copy
img[0,0,0]
img[0,0,0] = 127
copy[0,0,0]
copy[0,0,0] = 127
copy.shape
copy.shape[0]
copy.shape[1]
copy.shape[2]
dim = copy.shape
for row in range(dim[0]):
    for col in range(dim[1]):
        avg = np.sum(img[row,col,:])
        copy[row,col,:] = avg
        
        
mpimg.save("grey.png", copy)
mplt.image.imsave("grey.png", copy)
plt.image.imsave("grey.png", copy)
plt.imsave("grey.png", copy)
get_ipython().run_line_magic('s', 'greyscale-panda.py 1-25')
Beispiel #10
0
    def save2D(self, filename, img=None):
        """
		Save the Vignette as 2D image
		"""
        img = self.image2D() if img is None else img
        img.save(filename, format='png')
Beispiel #11
0
data = image.imread("data/input/q9_fig.jpg")
print(data.dtype)
print(data.shape)
print(data.max())
print(data.min())
pyplot.imshow(data)

image2 = Image.fromarray(data)
type(image2)

image = Image.open("data/input/q9_fig.jpeg")
data = asarray(image)
print(data.dtype)
print(data.shape)
image.save("data/input/q9_fig.png", format="PNG")
image.save("data/input/q9_fig.gif", format="GIF")
image3 = Image.open("data/input/q9_fig.gif")
print(image3.format)

image_gray = image.convert(mode="L")
image_gray
image_gray.save("data/input/q9_fig_gray.jpeg")
image_gray.thumbnail((100, 100))
image_gray

horizontal_image = image2.transpose(Image.FLIP_LEFT_RIGHT)
pyplot.imshow(horizontal_image)
vertical_image = image2.transpose(Image.FLIP_TOP_BOTTOM)
pyplot.imshow(vertical_image)
vertical_image = image2.transpose(Image.ROTATE_270)
Beispiel #12
0
def main():

        #have land cover and slope, reclassify land cover for impedance
        #have elevation map, use arcpy to calculate slope for each cell might not need this
        #use raster to numpy array to get numpy arrays of each thing
        #use formula from tobler to calculate walking speed across each cell
        #arc.env.workspace = "C:\Users\Eric Cawi\Documents\SAR\Motion Model Test"
        
        sl = misc.imread(base_dir + "slope.tif")
        sl = np.add(sl,.1)#get rid of divide by 0 errors
        sl = sl* np.pi/180.0 #convert slope to radians
        #have to resize image to make the arrays multiply correctly
        img = Image.open(base_dir + 'imp2.png')
        shp = np.shape(sl)
        shp = tuple(reversed(shp))#need to get in width x height instead of height x width for the resize
        img = img.resize(shp,Image.BILINEAR)
        img.save(base_dir + 'imp2.png')
        imp = misc.imread(base_dir + 'imp2.png')
        impedance_weight = .5
        slope_weight = .5
        #before getting inverse of slope use array to make walking speed array
        # for simplicity right now using tobler's hiking function and multiplying with the impedance weight
        walking_speeds = 6*np.exp(-3.5*np.abs(np.add(np.tan(sl),.05)))*1000.0/60.0 # speed in kmph*1000 m/km *1hr/60min
        sl = np.divide(1,sl)

        imp.astype('float')
        
  
        #walking speed weighted with land cover here from doherty paper, which uses a classification as 25 = 25% slower than normal, 100 = 100% slower than normal walking speed
        vel_weight = np.divide(np.subtract(100.0,imp),100.0)
        walking_speeds = np.multiply(vel_weight, walking_speeds) #since 1 arcsecond is roughy 30 meters the dimensions will hopefully work out
        
        #lower impedance is higher here, will work for probabilities, have to convert to float to avoid divide by zero errors
        imp = np.divide(1.0,imp)
        		
        print 'imp:', imp
        print 'sl:', sl
        print 'vw:', vel_weight
        res = 25000/shp[0]#30 meter impedance resolution from the land cover dataset
        end_time = 240#arbitrary 4 hours
        #establish initial conditions in polar coordinates, using polar coordinates because i think it's easier to deal with the angles
        #r is the radius from the last known point, theta is the angle from "west"/the positive x axis through the lkp
        r = np.zeros(NUM_SIMS)#simulates 1000 hikers starting at ipp
        theta = np.random.uniform(0,2*np.pi,NUM_SIMS) #another 1000x1 array of angles, uniformly distributing heading for simulation
        stay = .05
        rev = .05#arbitrary values right now, need to discuss
        sweep = [-45.0 , -35.0 , -25.0 , -15.0 , -5.0 , 5.0 , 15.0 , 25.0 , 35.0, 45.0 , 0.0 , 180.0] #0 represents staying put 180 is a change in heading
        for i in range(len(sweep)):
                sweep[i] = sweep[i]*np.pi/180.0 #convert sweep angles to radians
        dr = 120.0 #120 meters is four cells ahead in the land cover raster which gives 9 specific cells for the sweeping angles
        
        #for each lookahead, have ten angles between -45 and plus 45 degrees of the current heading
        #get average impedance around 100 meters ahead, average flatness, weight each one by half
        #then scale to 1 - (prob go back + prob stay put)  these guys are all free parameters I think

        for i in range(NUM_SIMS):
        	#print 'hiker: ',str(i)
        	#print 'current cell:'
        	current_cell = [shp[0]/2 - 1, shp[1]/2 - 1] #-1 is to compensate for the indeces starting at 0, starting at middle of array should represent the ipp
                t = 0.0
                current_r = r[i]
                current_theta = theta[i]
                while t < end_time:
                        #look in current direction, need to figure out how to do the sweep of slope
                        slope_sweep = attract(current_r, current_theta,current_cell,sweep,sl, res,dr)
                        impedance_sweep = attract(current_r,current_theta,current_cell,sweep, imp, res,dr)
                        #goal: have relative attractiveness of both slope and land cover by taking values
                        #for slope might have a function that takes the least average change in each direction
                        #then take reciprocal to make smaller numbers bigger and take each change/sum of total to get relative goodness
                        #land cover take average 1/impedance in each direction and get relative attractiveness
                        sl_w = np.multiply(slope_sweep,slope_weight)
                        imp_w = np.multiply(impedance_sweep, impedance_weight)
                        probabilities= np.add(sl_w, imp_w)

                        #create a random variable with each of the 12 choices assigned the appropopriate probability
                        dist = rv_discrete(values = (range(len(sweep)), probabilities))
                        ind = dist.rvs(size = 1)
                        dtheta = sweep[ind]
                        
                        #Note: cannot test floating point for equality!  Modified.  -crt
                        eps = 1e-4
                        if (-eps < dtheta < eps):
                                v = 0.0 #staying put, no change
                                dt = 10.0 #stay arbitrarily put for 10 minutes before making next decision
                                r_new = current_r
                                theta_new = current_theta + dtheta
                        elif (np.pi-eps < dtheta < np.pi + eps):#reversal case
                                v = avg_speed(current_cell, dtheta,dr,walking_speeds, res)
                                dt = dr/v
                                r_new = current_r-dr
                                theta_new = -1*current_theta
                        else:
                                #update the current hiker's new radius                          
                                if -eps < current_r < eps:
                                        r_new = dr
                                        theta_new = current_theta + dtheta 
                                else:
                                        r_new = np.sqrt(current_r**2 + dr**2 -2.0*current_r*dr*np.cos(np.pi-dtheta))#law of cosines to find new r
                                #law of sines to find new theta relative to origin, walking speeds treats each original cell as origin to calculate walking velocity
                                	asin = np.arcsin(dr* np.sin(np.pi-dtheta)/r_new )
                                	theta_new = current_theta+asin
                                v = avg_speed(current_cell,dtheta,dr,walking_speeds,res)#some way to figure out either average speed or distance traveled along the line chosen
                                dt = dr/v
                        #update for current time step
                        
                        current_r = r_new
                        current_theta= theta_new
                        t=t+dt
                        #print t
                        #update current_cell for slope and impedance
                        x = np.floor(current_r*np.cos(current_theta)/res)
                        y = np.floor(current_r*np.sin(current_theta)/res)
                        
                        current_cell = [y,x]#since the array was changed only need one current cell
                        
                #print current_cell
                        #print t
                        
                #update r and theta
                r[i] = current_r
                theta[i] = current_theta
                #print current_r, current_theta*180./np.pi
        #now that we have final positions for NUM_SIMS hikers at endtime the goal is to display/plot
        #Note: streamlined to eliminated some loops etc. -crt
        Xs = r * np.cos(theta)/50.
        Ys = r * np.sin(theta)/50.

        #Count the outsiders using vector logic: "OR" these arrays together
        outsiders = (Xs < -250) | (Xs > 250) | (Ys < -250) | (Ys > 250)
        num_outside = np.sum(outsiders)
        insiders = (-250<=Xs) & (Xs<=250) & (-250<=Ys) & (Ys<=250)
        num_inside = np.sum(insiders)
        prob_outside = 1. * num_outside / NUM_SIMS
        prob_inside = 1. * num_inside / NUM_SIMS

        # Create nominal grid of N 50m cells. Will get resized later.
        # Avoid zeros by putting 10/NUM_SIMS observations in each cell.
        # TODO: let prior be the distance model, with weight of ~1/100 motion model.
        bias = 10.
        counts = bias * np.ones((501,501)) / NUM_SIMS
        coords = zip(Ys, Xs)
        for y,x in coords:
                if -250<=x<=250 and -250<=y<=250:
                        counts[250+y][250+x] += 1

        probs = counts/(np.sum(counts)+bias)
        print 'SumCounts  :', np.sum(counts)
        print '\nCounts   :',counts
        print 'Probs\n', probs
        print '\nP_inside  :', prob_inside
        print 'P_outside :', prob_outside
        print 'Sum(probs):', np.sum(probs)
        case_name = 'test'
        #example plotting for testing:
        plt.title("Motion Model Test")
        plt.imshow(probs,cmap = 'gist_gray')
        plt.colorbar()
        name = '%s/%s.png' % (base_dir, case_name)
        plt.imsave(name, probs, cmap = 'gist_gray')
        tag_image(name, prob_outside)
    images = {}
    for i in range(len(imageNames)):
        image = img.imread(os.path.join(folder, imageNames[i]))
        images[imageNames[i]] = image
    return images


logging.basicConfig(format='%(levelname)s '
                    '%(processName)-10s : %(asctime)s '
                    '%(module)s.%(funcName)s:%(lineno)s %(message)s',
                    level=logging.INFO)
trainImageNames = os.listdir(
    'C:/Users/Anvitha/PycharmProjects/HCI/train_images')
images = loadImagesInToVector(
    'C:/Users/Anvitha/PycharmProjects/HCI/train_images', trainImageNames)
print(len(images))

for imagename, image in images.items():
    fig = plt.figure()
    plt.imshow(image)
    plt.colorbar()
    plt.title(
        "left click: line segment         right click or double click: close region"
    )
    plt.show(block=False)
    roi1 = RoiPoly(color='r', fig=fig)
    mask = roi1.get_mask(image)
    img = Image.fromarray(mask)
    img.save(
        os.path.join('C:/Users/Anvitha/PycharmProjects/HCI/mask/', imagename))
Beispiel #14
0
"""image = Image.open('Sydney-Opera-House.jpg')
print(image.format)
print(image.mode)
print(image.size)
image.show()"""

# load and display with Matplotlib

"""data = image.imread('Sydney-Opera-House.jpg')
print(data.dtype)
print(data.shape)
pyplot.imshow(data)
pyplot.show()"""

"""image = Image.open('Sydney-Opera-House.jpg')
image.save('opera-house.png',format='PNG')
image2 = Image.open('opera-house.png')
print(image2.format)"""

"""image = Image.open('Sydney-Opera-House.jpg')
gs_image = image.convert(mode='L')
gs_image.save('opera-house-grayscale.jpg')
image2 = Image.open('opera-house-grayscale.jpg')
image2.show();"""

"""image = Image.open('Sydney-Opera-House.jpg')
print(image.size)
image.thumbnail((100,50))
print(image.size)"""
Beispiel #15
0
for ind, cnt in enumerate(contours):
    x, y, w, h = cv2.boundingRect(cnt)

    if ind == 0:
        normal_contours = np.array([[x, y, w, h]])
    else:
        normal_contours = chek2(x, y, w, h, normal_contours)

sorr_con = sorted(normal_contours, key=lambda row: row[0])
for ind, ar in enumerate(sorr_con):
    x, y, w, h = ar
    t_img = img[y:y + h, x:x + w]
    t_img = cv2.resize(t_img, (32, 32))
    if not os.path.exists("data"):
        os.mkdir("data")
    save("data\\{}.png".format(ind), f(t_img))

res = np.array([], dtype="str")
for elem in os.listdir("data"):
    t_img = cv2.imread("data\\{}".format(elem))
    res = np.append(res, model.predict(t_img[:, :, 0].reshape((1, 32 * 32))))

import shutil
shutil.rmtree("data")

formula = ""
for c in res:
    formula += c
print(formula)

evaluation_of_func(