示例#1
0
文件: app.py 项目: Muzilos/pixeleat
    def __init__(self):
        pygame.display.set_caption("Visualizer")
        self.window = pygame.display.set_mode(size=(WIDTH, HEIGHT))
        self.window.fill([0, 0, 0])
        self.running = True
        self.top_pixels, self.bot_pixels = [], []

        # Top pixel
        self.top_color = Color(rgb=WHITE)
        self.top_pixel = Pixel(CENTER[0],
                               CENTER[1],
                               RADIUS,
                               self.top_color,
                               facing='RIGHT',
                               win=self.window)
        # Bottom pixel
        self.bot_color = Color(rgb=BLUE)
        self.bot_pixel = Pixel(CENTER[0],
                               CENTER[1],
                               RADIUS,
                               self.bot_color,
                               facing='LEFT',
                               win=self.window)

        self.sound = Sound()
    def __init__(self, radius, pixels_per_strip):
        self.radius = radius
        self.pixels_per_strip = pixels_per_strip

        # Form Pixels
        self.pixels = []
        theta = np.linspace(0, np.pi, pixels_per_strip)

        # Get coordinates
        x = np.cos(theta)
        y = np.zeros(len(theta))
        z = np.sin(theta)

        # How much to rotate the led strips by (about z axis)
        dtheta = np.pi / 16.0

        # First strip of leds, anticlockwise rotation
        cos_anti = np.cos(dtheta)
        sin_anti = np.sin(dtheta)

        x_anti = cos_anti * x - sin_anti * y
        y_anti = sin_anti * x + cos_anti * y

        for i in range(len(x)):
            self.pixels.append(Pixel(np.array([x_anti[i], y_anti[i], z[i]])))

        # Second strip of leds, clockwise rotation
        cos_clock = np.cos(np.pi - dtheta)
        sin_clock = np.sin(np.pi - dtheta)

        x_clock = cos_clock * x - sin_clock * y
        y_clock = sin_clock * x + cos_clock * y

        for i in range(len(x)):
            self.pixels.append(Pixel(np.array([x_clock[i], y_clock[i], z[i]])))
示例#3
0
 def __init__(self, color1=Pixel.fromHex("#FFFFFF"), color2=Pixel.fromHex("#000000"), ambient=0.05, diffuse=1.0, specular=1.0, reflection=0.5):
     self.color1 = color1
     self.color2 = color2
     self.ambient = ambient
     self.diffuse = diffuse
     self.specular = specular
     self.reflection = reflection
示例#4
0
def main():

    # 1st part: drawing curve and manipulate image color
    input_image = Image.open('zzz.jpg')
    pp0 = Pixel(30, 30)
    pp1 = Pixel(330, 30)
    C = Curve(input_image)
    cc = C.curve_draw(pp0, pp1, [(.2, 90), (.4, 350), (.6, 100), (.8, 80)])
    # cc = C.curve_draw(pp0, pp1, [(.2,90), (.4, 150), (.6, 100), (.8, 80)])
    # cc = C.curve_draw(pp0, pp1, [(.2,70), (.4, 100), (.6, 120), (.8, 80)])
    # cc = C.curve_draw(pp0, pp1, [(.2,90), (.4, 120), (.6, 100), (.8, 80)])
    C.image.show()
    print(cc)
    a, b, c = C.calc_parabola_vertex(int(cc[1][0]), int(cc[1][1]),
                                     int(cc[2][0]), int(cc[2][1]),
                                     int(cc[3][0]), int(cc[3][1]))
    C.color_map(a, b, c)
    C.image.show()
    print(a, b, c)

    # 2nd part: hue switching
    image_manipulation('zzz.jpg',
                       'Second_Image.png',
                       save_name='hue_modification.png')
    image_manipulation('zzz.jpg',
                       'Second_Image_1.png',
                       save_name='hue_modification_1.png')
    image_manipulation('zzz.jpg',
                       'Second_Image_2.png',
                       save_name='hue_modification_2.png')
示例#5
0
def analysis(input):
    """Analysis method"""
    
    # Add the input files to the ROOT chain
    chain = ROOT.TChain("CollectionTree")     
    for inputFile in input["input"]:
        chain.AddFile(inputFile)
    
    # Select all branches
    chain.SetBranchStatus("*", 1)
    
    # Intitialize histogramService
    histoSrv = HistogramService()
    
    # Create Histogram branches
    histoCalo = histoSrv.branch("Calorimeters")
    histoPixel = histoSrv.branch("Pixel detector")
    histoTRT = histoSrv.branch("TRT detector")
    histoTruth = histoSrv.branch("Truth information")
    # Initialize tools
    calo = Calo(chain, histoCalo)
    pixel = Pixel(chain, histoPixel)
    trt = TRT(chain, histoTRT)

    smpEvent = SMPEvent(chain, histoTruth)
    
    ## event loop    
    N_evts = 10000
    if chain.GetEntries() < N_evts:
        N_evts = chain.GetEntries()
    for i in xrange(N_evts):
        chain.GetEntry(i)
        smpEvent.GetEntry()
        
        ## Cuts
        # if chain.PassedL1_MU40 == 0: continue
        
        # Loop over tracks
        for trk in xrange(chain.Trk_N):
            
            # Track cuts for High_pT analysis
            if chain.Trk_p_T[trk] > 40000 and chain.Trk_eta[trk] < 1.7:
                calo.dedxLAr(trk)
                calo.dedxTile(trk)
                calo.alldedx(trk)
                pixel.dedx(trk)
                
                trt.betastuff(trk)
                trt.dedx_bit(trk)
               
            # Low pT plots 
            elif chain.Trk_p_T[trk] <= 10000:
                calo.lowdedx(trk)
    
    
    
    # Return histogram service for merging
    return histoSrv.returnTree()
示例#6
0
 def draw(self, screen):
     for _ in range(len(self.mes)):
         location = [
             (self.mes[_][0][0] - 1) * self.pixelScale[0] +
             self.shifting[0],
             (self.mes[_][0][1]) * self.pixelScale[1] + self.shifting[1]
         ]
         color = self.mes[_][1]
         pixel = Pixel(self.pixelScale, location, color)
         pixel.draw(screen)
示例#7
0
 def __init__(self):
     self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN,
                                    self.LED_FREQ_HZ, self.LED_DMA,
                                    self.LED_INVERT, self.LED_BRIGHTNESS)
     self.strip.begin()
     self.pixels = map(lambda x: Pixel(x, colors.black),
                       list(range(self.num_pixels())))
示例#8
0
def parse(filename, jpg):
    nc_dataset = Dataset(filename, "r")  # read-only
    nc_attrs, nc_dims, nc_vars = ncdump(nc_dataset)

    data = nc_dataset.variables["Sigma0_VV_dB"][:].T

    # mode = 50.5-52.5

    # for (x, y) in zip(range(len(data)), range(len(data[x]))):
    #     # val = data[x][y]
    #     # if isinstance(val, numbers.Number) and val > 0.003:
    #     #     data_list.append(val)
    #
    #     pixel = Pixel(x, y, data[x][y])
    #     if isinstance(pixel.sigma0, numbers.Number) and pixel.sigma0 > 10**-3:
    #         data_list.append(pixel)

    # holy shit

    data_list = [
        el for sublist in [[
            Pixel(x, y, val) for y, val in enumerate(_data)
            if isinstance(val, numbers.Number) and abs(val) > 0.003
        ] for x, _data in enumerate(data)] for el in sublist
    ]
    np_data = np.asarray(data_list).reshape(1, len(data_list))

    # np_data = data.reshape(1, data.size)

    mu, cluster_data = fuzzy_1d.isolate_cluster(np_data, 2)

    threshold, threshold_data = fuzzy_1d.threshold(mu, cluster_data)
    fuzzy_1d.visualize_fuzzy(np_data, threshold_data, jpg_img)
示例#9
0
    def __init__(self):

        self.strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ,
                                       LED_DMA, LED_INVERT, LED_BRIGHTNESS)
        self.strip.begin()

        self.program = Program(self.strip, PIXEL_AMOUNT)
        self.currentProcess = None
        '''Create pixels'''
        '''195 leds in the 8 pixels'''
        self.pixels = []
        ind = 0
        for p in range(0, PIXEL_AMOUNT):
            if p == 0 or p == 7:
                amount = 26
            elif p == 8:
                amount = 40
            elif p == 9:
                amount = 41
            else:
                amount = 27
            pixel = Pixel(ind, amount)
            ind = ind + amount

            self.pixels.append(pixel)
示例#10
0
    def init_pixels(self, surface=None):
        self.pixels.clear()

        if surface is None:
            # Alocate memory for the pixels
            for y in range(self.size.y):
                self.pixels.append([])

                for x in range(self.size.x):
                    self.pixels[y].append(None)

            self.clear(WHITE)
        else:
            # Load image (for example .png)
            self.surface = surface.copy()
            self.size = Vec2(self.surface.get_width(),
                             self.surface.get_height())
            self.scaled_size = Vec2(self.size.x * self.zoom,
                                    self.size.y * self.zoom)
            self.origin = Vec2(self.size.x / 2, self.size.y / 2)
            self.scaled_origin = Vec2(self.origin.x * self.zoom,
                                      self.origin.y * self.zoom)

            for y in range(self.size.x):
                self.pixels.append([])

                for x in range(self.size.y):
                    color = surface.get_at((x, y))
                    self.pixels[y].append(Pixel(Vec2(x, y), color.copy()))

            self.update_pixels()
示例#11
0
    def find_pixels(self):
        print "Finding pixels..."
        self.pixels = []
        self.colors = {}  #all kinds of colors in image
        for x in xrange(self.inside_img.shape[0]):
            for y in xrange(self.inside_img.shape[1]):
                rgb_values = self.inside_img[x, y]
                if sum(rgb_values) != 3 * 255:  #white

                    #increasing saturation
                    rgb = [item / float(255) for item in rgb_values]
                    hsv = list(colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2]))

                    if hsv[0] == 0 and hsv[1] == 0:  #if black or grey shade
                        hsv[2] = 0  #set value to 0 (pure black)

                    else:  #if any color other than black
                        hsv[1] = 1  #set saturation to max value
                        hsv[2] = 1  #set value to max value

                    rgb_values = list(
                        colorsys.hsv_to_rgb(hsv[0], hsv[1],
                                            hsv[2]))  #convert back to rgb
                    rgb_values = [item * 255
                                  for item in rgb_values]  #normalize to 255

                    new_pixel = Pixel(y, x, rgb_values[0], rgb_values[1],
                                      rgb_values[2])

                    rgb_tuple = tuple(rgb_values)
                    if rgb_tuple not in self.colors:
                        self.colors[rgb_tuple] = 1
                    else:
                        self.colors[rgb_tuple] += 1
                    self.pixels.append(new_pixel)
示例#12
0
    def get_pixels(self):
        dest = []
        cur = self.con.cursor()

        for el in cur.execute(f"SELECT * FROM {TABLE} ORDER BY id"):
            dest.append(Pixel(el))
        return dest
示例#13
0
    def visualize(self, polygons, light, size):
        matrix = [[Pixel() for i in range(size[1])] for j in range(size[0])]
        for polygon in polygons:
            if polygon is None:
                continue
            color = self._get_color(polygon, light)
            points = polygon.points
            points = sorted(points, key=lambda point: (-point[1], point[0]))
            plane = Plane(points)
            if plane.get_coefficient_z() == 0:
                continue
            if points[0][1] != points[1][1]:
                first_straight = Straight(points[0], points[1])
                second_straight = Straight(points[0], points[2])
                self._set_triangle(points[0][1], points[1][1], first_straight,
                                   second_straight, plane, matrix, color)
            if points[1][1] != points[2][1]:
                first_straight = Straight(points[1], points[2])
                second_straight = Straight(points[0], points[2])
                self._set_triangle(points[1][1], points[2][1], first_straight,
                                   second_straight, plane, matrix, color)
        if light[2] < 0:
            width = len(matrix)
            height = len(matrix[0])
            x = int(light[0] + width / 2)
            y = int(height / 2 - light[1])
            self._set_pixel(x, y, 0, matrix, (255, 0, 0))

        return matrix
    def convert_to_html(self):
        """
        Creates a new HTML image that is built by averaging blocks of pixels of
        a given size.
        """

        html = "<table style='table-layout:fixed; border-spacing: 0;width:{w}px; height:{h}px; border: 1px solid green;'>".format(w=self.width, h=self.height)

        j = 0
        while j < self.height:
            i = 0

            html += "<tr>"
            while i < self.width:

                block_pixels = []
                for jx in xrange(j, j+self.block_size+1):
                    for ix in xrange(i, i+self.block_size+1):
                        if ix < self.width and jx < self.height:
                            block_pixels.append(self._get_pixel(ix, jx))

                if len(block_pixels) > 0:
                    avg_pixel = Pixel.avg_pixels(block_pixels)
                    html += HtmlBlockEmbedder.PIXEL_HTML_TEMPLATE.format(w=self.block_size, h=self.block_size, hex_color=avg_pixel.to_hex_string())

                i += self.block_size

            j += self.block_size

            html += "</tr>"

        html += "</table>"
        return html
示例#15
0
    def clear(self, color: Vec4):
        for y in range(self.size.y):
            for x in range(self.size.x):
                self.pixels[y][x] = Pixel(Vec2(x, y), color.copy())

        self.surface.fill(color.as_tuple())
        self.changed_pixels.clear()
示例#16
0
    def test_create_pixel(self):

        p = Pixel(100, 200, 1234, -1, 256, 256)

        # The tests
        #-----------
        self.assertEqual(p.get_x(), 100)
        self.assertEqual(p.get_y(), 200)
        self.assertEqual(p.getX(), 51300)
        self.assertEqual(p.getC(), 1234)
        self.assertEqual(p.get_mask(), -1)
        self.assertEqual(p.get_neighbours(), {})
        self.assertEqual(p.pixel_entry(),
                         "{\"x\":100, \"y\":200, \"c\":1234},\n")
示例#17
0
    def get_pixel(self, id):
        cur = self.con.cursor()
        res = cur.execute(f"SELECT * FROM {TABLE} WHERE id=:id", {
            "id": id
        }).fetchone()

        if (res == None):
            return None
        return Pixel(res)
示例#18
0
def find_nearest_floss(region_point):
    error = [
        sum_squared_error(region_point,
                          Pixel.FromRGB(floss['rgb']).get_Lab())
        for floss in dmc_flosses.flosses
    ]
    best_error = min(error)
    idx = error.index(best_error)
    return dmc_flosses.flosses[idx]
示例#19
0
    def createUI(self, parent):
        parent.columnconfigure(0, weight=0)
        parent.columnconfigure(1, weight=1, minsize=200)

        ttk.Label(parent, text="Linear Array").grid(column=0,
                                                    row=1,
                                                    sticky=(W, E))
        ttk.Label(parent, text="Pixel Count:").grid(column=0,
                                                    row=2,
                                                    sticky=(W, E))
        ttk.Label(parent, text=str(self.strip.numPixels())).grid(column=1,
                                                                 row=2,
                                                                 sticky=(W, E))
        ttk.Label(parent, text="Brightness:").grid(column=0,
                                                   row=3,
                                                   sticky=(W, E))
        ttk.Scale(parent,
                  orient=HORIZONTAL,
                  from_=0,
                  to=255,
                  value=self.strip.getBrightness(),
                  command=self.setBrightness).grid(column=1,
                                                   row=3,
                                                   sticky=(W, E))

        self.effect_box = ttk.Combobox(parent,
                                       values=("Single", "Fade", "Christmas",
                                               "Script"),
                                       state='readonly')
        self.effect_box.current(0)
        self.effect_box.bind("<<ComboboxSelected>>", self.effectChanged)
        self.effect_box.grid(column=0, row=4, sticky=(N, W, E))

        self.effect_frame = ttk.LabelFrame(parent, text='Effect')
        self.effect_frame.grid(column=1, row=4, sticky=(W, E))
        self.effect_frame.columnconfigure(0, weight=0)
        self.effect_frame.columnconfigure(1, weight=1)
        self.effect.createUI(self.effect_frame)

        self.canvas = Canvas(parent, background="#FFFFFF")
        self.canvas.grid(column=0, row=5, columnspan=2, sticky=(N, W, E, S))

        self._drag_data = {"x": 0, "y": 0, "drag": False}
        self._select_data = {"x": 0, "y": 0, "id": None}

        self.canvas.tag_bind("pixel", "<ButtonPress-1>",
                             self.onPixelButtonPress)
        self.canvas.tag_bind("pixel", "<ButtonRelease-1>",
                             self.onPixelButtonRelease)
        self.canvas.tag_bind("pixel", "<B1-Motion>", self.onPixelMotion)

        self.canvas.bind("<ButtonPress-1>", self.onButtonPress)
        self.canvas.bind("<ButtonRelease-1>", self.onButtonRelease)
        self.canvas.bind("<B1-Motion>", self.onMotion)

        for i in range(0, 20):
            self.pixels.append(Pixel(self.strip, self.canvas, (20 * i) + 5, 5))
示例#20
0
def find_nearest_floss(block):
    # This way searches full blown sum of squared error for best color
    #error = [block.color_error(floss['rgb']) for floss in dmc_flosses.flosses]
    # This way does a jenky averaged color search
    average_point = [average(coord) for coord in zip(*block.points)]
    error = [sum_squared_error(average_point, Pixel.FromRGB(floss['rgb']).get_Lab()) for floss in dmc_flosses.flosses]
    best_error = min(error)
    idx = error.index(best_error)
    return dmc_flosses.flosses[idx]
示例#21
0
    def find_all_stars_on_image(self, header, image_data, nPixels=0):
        '''
            given image-data (and associated header) use refcat to find all of the stars that fall on the image
            
            inputs:
            -------
            
            returns:
            --------
            pixels / (ra,dec) / both ???
        '''

        # Identify integer RAs & Decs in the data: uses WCS:
        # Then find unique PAIRS of ra,dec integers
        sky_coords = Pixel().get_per_pixel_RADEC(header, image_data)
        int_radec = np.unique(np.array([
            np.around(sky_coords.ra.degree).astype(int).flatten(),
            np.around(sky_coords.dec.degree).astype(int).flatten()
        ]).T,
                              axis=0)

        # search refcat around those integer ra-dec pairs
        code = self.refcat_filepath
        dir = os.path.join(self.refcat_dir, '00_m_16')
        rad = 1
        mlim = 20
        print("\
              **\
              WARNING: HARD-CODED MAG-LIMITS & SEARCH DIRECTORIES IN find_all_stars_on_image()\
              **\
              ")
        results_dict = {}
        for ra, dec in int_radec:
            results_dict.update(
                self._read_refcat(ra, dec, code, dir, rad=rad, mlim=mlim))

        # get pixels corresponding to  (ra, dec)'s of catalog sources
        ra = np.array([v[0] for v in results_dict.values()])
        dec = np.array([v[1] for v in results_dict.values()])
        pix = np.array(WCS(header).all_world2pix(ra, dec, 1))
        int_pix = np.around(pix).astype(int)

        # offset pixels because of offset between numpy & fits-fortran
        pix = pix - 1
        int_pix = int_pix - 1

        # remove sources which would be more than n-Pixels from the edge of the image
        ind = (int_pix[0] > -nPixels) & \
              (int_pix[0] < nPixels + header['NAXIS1']) & \
              (int_pix[1] > -nPixels) & \
              (int_pix[1] < nPixels + header['NAXIS2'])

        return  ra[ind],\
                dec[ind] ,\
                np.array( [pix[0][ind], pix[1][ind] ]),\
                np.array([int_pix[0][ind], int_pix[1][ind] ])
示例#22
0
    def add_hexes(self):
        """cellmap is a dictionary of { coord: pixel object }"""
        cellmap = {}

        for h in range(self.hexes):
            for x in range(-self.hex_offset, self.hex_offset + 1):
                y_adj = -(self.hex_offset + x) if x < 0 else -self.hex_offset
                for y in range(self.size - abs(x)):
                    cellmap[(h, x, y + y_adj)] = Pixel(h, x, y + y_adj)
        return cellmap
示例#23
0
 def __init__(self, x, y, width, height):
     super(Sprite, self).__init__(x, y, width, height, pygame.image.load('resources/checkered.png'))
     self.pixels = []
     #TODO we can calculate pixel w/h using sprite Dim and w/h of sprite surface
     self.pixel_width = 2
     self.pixel_height = 2
     #TODO pixels in sprite should perhaps be the width and height, remove current width and height
     self.sprite_width = 20
     self.sprite_height = 20
     self.block_width, self.block_height = (self.frame.w / self.sprite_width, self.frame.h / self.sprite_height)
     #TODO self.pixels does not need to be a double array. Pixel objects know their location once set so we only need
     #ToDo a list of them
     for y in range(self.sprite_width):
         for x in range(self.sprite_height):
             pixel = Pixel(x * self.block_width, y * self.block_height, self.block_width, self.block_height)
             pixel.set_parent(self)
             self.add(pixel)
             self.pixels.append(pixel)
     self.color_box = None
示例#24
0
def click(event):
    if len(road_pixels) < 3:
        print("clicked at", event.x, event.y)
        road_pixels.append(Pixel((event.x, event.y)))
        if len(road_pixels) == 2:
            calc_pixel_line()
            draw_line()
    elif len(road_pixels) > 2:
        print("Reaching coloring part")
        draw_road()
示例#25
0
 def curve_draw(self, p0, p1, pt_list, line_width=3):
     # pt_list.remove(pt_list[0])
     # pt_list.remove(pt_list[-1])
     xList = []
     yList = []
     param = len(pt_list)
     pdt = p0 - p1
     p = Pixel(0, 0)
     draw = ImageDraw.Draw(self.image)
     for i in range(param):
         temp_pt = Pixel(pt_list[i][0], pt_list[i][1])
         p.x = p0.x + pdt.x * temp_pt.x
         p.y = temp_pt.y
         xList.append(p.x)
         yList.append(p.y)
         # if i < param + 1:
         #     draw.line((p0.x,p0.y,p.x,p.y), fill=(255,0,0), width=line_width)
         #     self.curve_pixs.append(Pixel(int(p.x + 0.5), int(p.y + 0.5)))
         #     p0.x, p0.y = p.x, p.y
         # else:
         #     draw.line((p.x,p.y,p1.x,p1.y), fill=(255,0,0), width=line_width)
         #     self.curve_pixs.append(Pixel(int(p.x + 0.5), int(p.y + 0.5)))
     m = 100000  # of steps
     for p in range(m):
         x = (self.image.size[0] - 1) * p / (m - 1)
         y = 0.0
         for j in range(param):
             Lx = 1.0
             for k in range(param):
                 if k != j:
                     Lx = Lx * (x - xList[k]) / (xList[j] - xList[k])
             y = y + yList[j] * Lx
         if y >= 0 and y <= self.image.size[1] - 1:
             self.image.putpixel((int(x), int(y)), (255, 255, 255))
     # show the points used
     cr = 3  # circle radius
     for i in range(param):
         cx = int(xList[i])
         cy = int(yList[i])
         draw.ellipse((cx - cr, cy - cr, cx + cr, cy + cr))
     self.image.save('Polynomial_Interpolation.png', 'PNG')
     return list(zip(xList, yList))
示例#26
0
    def test_create_pixel(self):

        p = Pixel(100, 200, 1234, -1, 256, 256)

        # The tests
        # -----------
        self.assertEqual(p.get_x(), 100)
        self.assertEqual(p.get_y(), 200)
        self.assertEqual(p.getX(), 51300)
        self.assertEqual(p.getC(), 1234)
        self.assertEqual(p.get_mask(), -1)
        self.assertEqual(p.get_neighbours(), {})
        self.assertEqual(p.pixel_entry(), '{"x":100, "y":200, "c":1234},\n')
    def __init__(self, base, length, direction, nPixels):
        ''' base is the coordinate of the base pixel
            length is the length of the strip
            dirrection is a vector of linear strip direction]
        '''
        self.base = base
        self.length = length
        self.direction = direction / np.linalg.norm(direction)

        dP = (self.length / float(nPixels - 1)) * self.direction
        self.pixels = [Pixel(self.base + i * dP) for i in range(nPixels)]
示例#28
0
    def add_pixels():
        """cellmap is a dictionary of { coord: pixel object }
           could do this as a complicated one-liner, but not worth the obscurity"""
        cellmap = {}

        for BIG_X, BIG_Y in BIG_COORD:
            for x in range(SQUARE_SIZE):
                for y in range(SQUARE_SIZE):
                    x_coord = x + (BIG_X * SQUARE_SIZE)
                    y_coord = y + (BIG_Y * SQUARE_SIZE)
                    cellmap[(x_coord, y_coord)] = Pixel(x_coord, y_coord)
        return cellmap
示例#29
0
    def create_screen(self, width, height, color):
        screen = []

        for x in range(0, width + 1):
            line = []

            for y in range(0, height + 1):
                line.append(Pixel(x, y, color))

            screen.append(line)

        return screen
示例#30
0
 def curve_draw(self, image, p0, p1, param=10, line_width=3):
     pdt = p0 - p1
     i = 0
     while i <= 1:
         p = p0 + pdt * i
         draw = ImageDraw.Draw(image)
         # print(p.x, ' | ', p.y)
         draw.line((p0.x, p0.y, p.x, p.y),
                   fill=(255, 0, 0),
                   width=line_width)
         self.curve_pixs.append(Pixel(int(p.x + 0.5), int(p.y + 0.5)))
         p0 = p
         i += 1 / param
示例#31
0
    def create_pixels(picture):
        """

        :param picture: the inisital picture which consisted of a fundamental data types
        (i.e., represented pixels as 3-tuples)
        :return: a 2D array of Pixel objects.
        """
        rows = []
        for orig_row in picture:
            row = []
            for pixel in orig_row:
                row.append(Pixel(pixel[0], pixel[1], pixel[2]))
            rows.append(row)
        return rows
示例#32
0
    def get_image_data(self):
        tuples = self.origin.getdata()
        width = self.origin.width

        raw_data = self.origin.getdata()

        img_data = []
        for y in range(self.origin.height):

            row = [
                Pixel(tup=raw_data[tup])
                for tup in range(y * width, y * width + width)
            ]
            img_data.append(row)
        return img_data
 def begin(self,
           draw_matrix=False,
           width=0,
           height=0,
           window_w=1765,
           window_h=400):
     self.gui = NeoPixel_Emulator(window_w=window_w, window_h=window_h)
     self.pixel_list = list()
     for pixel in range(self.pixel_number):
         self.pixel_list.append(Pixel(pixel))
     if draw_matrix:
         self.gui.draw_LED_matrix(width, height)
     else:
         self.gui.draw_LEDs(self.pixel_number)
     self.gui.render()
示例#34
0
    def rainbow(self):
        # Initialise pixels
        pixelCount = 60
        pixels = []
        self.start()
        for x in range(0,pixelCount):
            pixels.append(Pixel(255,0,0))
            for loop in range(0,x):
                for r in range (0,4):
                    pixels[x].rotateColour()
            self.rgbPixel(pixels[x])
        self.end()

        while (self.stopped() == False):
            time.sleep(0.5)
示例#35
0
    def add_edge(self):
        self.lines.pop(0)                          # Remove 'l"
        arguments = self.lines.pop(0)              # Get Arguments

        # "Listify" Arguments
        arguments = arguments.split(" ")

        # Setup Pixel
        temp = Pixel()
        temp.set_red_num( int( arguments[6] ) )
        temp.set_green_num( int( arguments[7] ) )
        temp.set_blue_num( int( arguments[8] ) )

        # Edit edge matrix
        self.edge.add_edge( int( arguments[0] ),
                            int( arguments[1] ),
                            int( arguments[2] ),
                            int( arguments[3] ),
                            int( arguments[4] ),
                            int( arguments[5] ),
                            temp )
def mask_to_bin(mask):
    new = np.array(mask,tuple)
    print(new)
    for i in range(len(new)/pixel_size):
        new[i] = pix.mult_by_const(new[i],1./255)