Python pygame 模块,surfarray() 实例源码

我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用pygame.surfarray()

项目:Projects    作者:it2school    | 项目源码 | 文件源码
def slow_down_sound(sound, rate):
    """  returns a sound which is a slowed down version of the original.
           rate - at which the sound should be slowed down.  eg. 0.5 would be half speed.
    """

    raise NotImplementedError()
    grow_rate = 1 / rate

    # make it 1/rate times longer.

    a1 = sndarray.array(sound)

    surf = pygame.surfarray.make_surface(a1)
    print (a1.shape[0] * grow_rate)
    scaled_surf = pygame.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
    print (scaled_surf)
    print (surf)

    a2 = a1 * rate
    print (a1.shape)
    print (a2.shape)
    print (a2)
    sound2 = sndarray.make_sound(a2.astype(int16))
    return sound2
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_array3d(self):
        if not arraytype:
            self.fail("no array package installed")

        sources = [self._make_src_surface(16),
                   self._make_src_surface(16, srcalpha=True),
                   self._make_src_surface(24),
                   self._make_src_surface(32),
                   self._make_src_surface(32, srcalpha=True)]
        palette = self.test_palette

        for surf in sources:
            arr = pygame.surfarray.array3d(surf)
            def same_color(ac, sc):
                return (ac[0] == sc[0] and
                        ac[1] == sc[1] and
                        ac[2] == sc[2])
            for posn, i in self.test_points:
                self.failUnless(same_color(arr[posn], surf.get_at(posn)),
                                "%s != %s: flags: %i, bpp: %i, posn: %s" %
                                (tuple(arr[posn]),
                                 surf.get_at(posn),
                                 surf.get_flags(), surf.get_bitsize(),
                                 posn))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_map_array(self):
        if not arraytype:
            self.fail("no array package installed")

        arr3d = self._make_src_array3d(uint8)
        targets = [self._make_surface(8),
                   self._make_surface(16),
                   self._make_surface(16, srcalpha=True),
                   self._make_surface(24),
                   self._make_surface(32),
                   self._make_surface(32, srcalpha=True)]
        palette = self.test_palette

        for surf in targets:
            arr2d = pygame.surfarray.map_array(surf, arr3d)
            for posn, i in self.test_points:
                self.failUnlessEqual(arr2d[posn], surf.map_rgb(palette[i]),
                                     "%i != %i, bitsize: %i, flags: %i" %
                                     (arr2d[posn], surf.map_rgb(palette[i]),
                                      surf.get_bitsize(), surf.get_flags()))

        # Exception checks
        self.failUnlessRaises(ValueError, pygame.surfarray.map_array,
                              self._make_surface(32),
                              self._make_array2d(uint8))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_pixels2d(self):
        if not arraytype:
            self.fail("no array package installed")

        sources = [self._make_surface(8),
                   self._make_surface(16, srcalpha=True),
                   self._make_surface(32, srcalpha=True)]

        for surf in sources:
            self.failIf(surf.get_locked())
            arr = pygame.surfarray.pixels2d(surf)
            self.failUnless(surf.get_locked())
            self._fill_array2d(arr, surf)
            surf.unlock()
            self.failUnless(surf.get_locked())
            del arr
            self.failIf(surf.get_locked())
            self.failUnlessEqual(surf.get_locks(), ())
            self._assert_surface(surf)

        # Error checks
        self.failUnlessRaises(ValueError,
                              pygame.surfarray.pixels2d,
                              self._make_surface(24))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_surf_lock (self):
        if not arraytype:
            self.fail("no array package installed")

        sf = pygame.Surface ((5, 5), 0, 32)
        for atype in pygame.surfarray.get_arraytypes ():
            pygame.surfarray.use_arraytype (atype)

            ar = pygame.surfarray.pixels2d (sf)
            self.assertEquals (sf.get_locked (), True)

            sf.unlock ()
            self.assertEquals (sf.get_locked (), True)

            del ar
            self.assertEquals (sf.get_locked (), False)
            self.assertEquals (sf.get_locks (), ())

        #print ("test_surf_lock - end")
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def slow_down_sound(sound, rate):
    """  returns a sound which is a slowed down version of the original.
           rate - at which the sound should be slowed down.  eg. 0.5 would be half speed.
    """

    raise NotImplementedError()
    grow_rate = 1 / rate

    # make it 1/rate times longer.

    a1 = sndarray.array(sound)

    surf = pygame.surfarray.make_surface(a1)
    print (a1.shape[0] * grow_rate)
    scaled_surf = pygame.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
    print (scaled_surf)
    print (surf)

    a2 = a1 * rate
    print (a1.shape)
    print (a2.shape)
    print (a2)
    sound2 = sndarray.make_sound(a2.astype(int16))
    return sound2
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_get_arraytypes(self):
        if not arraytype:
            self.fail("no array package installed")

        arraytypes = pygame.surfarray.get_arraytypes()
        try:
            import numpy
        except ImportError:
            self.failIf('numpy' in arraytypes)
        else:
            self.failUnless('numpy' in arraytypes)

        try:
            import Numeric
        except ImportError:
            self.failIf('numeric' in arraytypes)
        else:
            self.failUnless('numeric' in arraytypes)

        for atype in arraytypes:
            self.failUnless(atype in ['numpy', 'numeric'],
                            "unknown array type %s" % atype)
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_make_surface(self):
        if not arraytype:
            self.fail("no array package installed")

        # How does one properly test this with 2d arrays. It makes no sense
        # since the pixel format is not entirely dependent on element size.
        # Just make sure the surface pixel size is at least as large as the
        # array element size I guess.
        #
        for bitsize, dtype in [(8, uint8), (16, uint16), (24, uint32)]:
## Even this simple assertion fails for 2d arrays. Where's the problem?
##            surf = pygame.surfarray.make_surface(self._make_array2d(dtype))
##            self.failUnless(surf.get_bitsize() >= bitsize,
##                            "not %i >= %i)" % (surf.get_bitsize(), bitsize))
##
            surf = pygame.surfarray.make_surface(self._make_src_array3d(dtype))
            self._assert_surface(surf)
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_surf_lock (self):
        if not arraytype:
            self.fail("no array package installed")

        sf = pygame.Surface ((5, 5), 0, 32)
        for atype in pygame.surfarray.get_arraytypes ():
            pygame.surfarray.use_arraytype (atype)

            ar = pygame.surfarray.pixels2d (sf)
            self.assertEquals (sf.get_locked (), True)

            # Numpy uses the Surface's buffer.
            if atype == "numeric":
                self.assertEquals (sf.get_locks (), (ar,))

            sf.unlock ()
            self.assertEquals (sf.get_locked (), True)

            del ar
            self.assertEquals (sf.get_locked (), False)
            self.assertEquals (sf.get_locks (), ())

        #print ("test_surf_lock - end")
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def setUp(self):
        # Needed for 8 bits-per-pixel color palette surface tests.
        pygame.init()

        # Makes sure the same array package is used each time.
        if arraytype:
            pygame.surfarray.use_arraytype(arraytype)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_array2d(self):
        if not arraytype:
            self.fail("no array package installed")

        sources = [self._make_src_surface(8),
                   self._make_src_surface(16),
                   self._make_src_surface(16, srcalpha=True),
                   self._make_src_surface(24),
                   self._make_src_surface(32),
                   self._make_src_surface(32, srcalpha=True)]
        palette = self.test_palette
        alpha_color = (0, 0, 0, 128)

        for surf in sources:
            arr = pygame.surfarray.array2d(surf)
            for posn, i in self.test_points:
                self.failUnlessEqual(arr[posn], surf.get_at_mapped(posn),
                                     "%s != %s: flags: %i, bpp: %i, posn: %s" %
                                     (arr[posn],
                                      surf.get_at_mapped(posn),
                                      surf.get_flags(), surf.get_bitsize(),
                                      posn))

            if surf.get_masks()[3]:
                surf.fill(alpha_color)
                arr = pygame.surfarray.array2d(surf)
                posn = (0, 0)
                self.failUnlessEqual(arr[posn], surf.get_at_mapped(posn),
                                     "%s != %s: bpp: %i" %
                                     (arr[posn],
                                      surf.get_at_mapped(posn),
                                      surf.get_bitsize()))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_arraytype(self):
        if not arraytype:
            self.fail("no array package installed")

        self.failUnless((pygame.surfarray.get_arraytype() in
                         ['numpy']),
                        ("unknown array type %s" %
                         pygame.surfarray.get_arraytype()))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_arraytypes(self):
        if not arraytype:
            self.fail("no array package installed")

        arraytypes = pygame.surfarray.get_arraytypes()
        self.failUnless('numpy' in arraytypes)

        for atype in arraytypes:
            self.failUnless(atype in ['numpy'],
                            "unknown array type %s" % atype)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_make_surface(self):
        if not arraytype:
            self.fail("no array package installed")

        # How does one properly test this with 2d arrays. It makes no sense
        # since the pixel format is not entirely dependent on element size.
        # Just make sure the surface pixel size is at least as large as the
        # array element size I guess.
        #
        for bitsize, dtype in [(8, uint8), (16, uint16), (24, uint32)]:
## Even this simple assertion fails for 2d arrays. Where's the problem?
##            surf = pygame.surfarray.make_surface(self._make_array2d(dtype))
##            self.failUnless(surf.get_bitsize() >= bitsize,
##                            "not %i >= %i)" % (surf.get_bitsize(), bitsize))
##
            surf = pygame.surfarray.make_surface(self._make_src_array3d(dtype))
            self._assert_surface(surf)

        # Issue #81: round from float to int
        try:
            rint
        except NameError:
            pass
        else:
            w = 9
            h = 11
            length = w * h
            for dtype in [float32, float64]:
                farr = arange(0, length, dtype=dtype)
                farr.shape = w, h
                surf = pygame.surfarray.make_surface(farr)
                for x in range(w):
                    for y in range(h):
                        self.assertEqual(surf.get_at_mapped((x, y)),
                                         int(rint(farr[x, y])))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def _test_pixels_rgb(self, operation, mask_posn):
        method_name = "pixels_" + operation
        if not arraytype:
            self.fail("no array package installed")

        pixels_rgb = getattr(pygame.surfarray, method_name)
        palette = [(0, 0, 0, 255),
                   (5, 13, 23, 255),
                   (29, 31, 37, 255),
                   (131, 157, 167, 255),
                   (179, 191, 251, 255)]
        plane = [c[mask_posn] for c in palette]

        surf24 = self._make_src_surface(24, srcalpha=False, palette=palette)
        surf32 = self._make_src_surface(32, srcalpha=False, palette=palette)
        surf32a = self._make_src_surface(32, srcalpha=True, palette=palette)

        for surf in [surf24, surf32, surf32a]:
            self.failIf(surf.get_locked())
            arr = pixels_rgb(surf)
            self.failUnless(surf.get_locked())
            surf.unlock()
            self.failUnless(surf.get_locked())

            for (x, y), i in self.test_points:
                self.failUnlessEqual(arr[x, y], plane[i])

            del arr
            self.failIf(surf.get_locked())
            self.failUnlessEqual(surf.get_locks(), ())

        # Check exceptions.
        targets = [(8, False),
                   (16, False),
                   (16, True)]

        for bitsize, srcalpha in targets:
            self.failUnlessRaises(ValueError, pixels_rgb,
                                  self._make_surface(bitsize, srcalpha))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_use_arraytype(self):
        if not arraytype:
            self.fail("no array package installed")

        def do_use_arraytype(atype):
            pygame.surfarray.use_arraytype(atype)

        pygame.surfarray.use_arraytype('numpy')
        self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numpy')

        self.failUnlessRaises(ValueError, do_use_arraytype, 'not an option')
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def setUp(self):
        # Needed for 8 bits-per-pixel color palette surface tests.
        pygame.init()

        # Makes sure the same array package is used each time.
        if arraytype:
            pygame.surfarray.use_arraytype(arraytype)
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_array2d(self):
        if not arraytype:
            self.fail("no array package installed")
        if arraytype == 'numeric':
            # This is known to fail with Numeric (incompatible
            # get_rgb and array element types).
            return

        sources = [self._make_src_surface(8),
                   self._make_src_surface(16),
                   self._make_src_surface(16, srcalpha=True),
                   self._make_src_surface(24),
                   self._make_src_surface(32),
                   self._make_src_surface(32, srcalpha=True)]
        palette = self.test_palette
        alpha_color = (0, 0, 0, 128)

        for surf in sources:
            arr = pygame.surfarray.array2d(surf)
            map_rgb = surf.map_rgb
            for (x, y), i in self.test_points:
                self.failUnlessEqual(arr[x, y], map_rgb(palette[i]),
                                     "%s != %s: flags: %i, bpp: %i, posn: %s" %
                                     (arr[x, y],
                                      map_rgb(palette[i]),
                                      surf.get_flags(), surf.get_bitsize(),
                                      (x, y)))

            if surf.get_masks()[3]:
                surf.fill(alpha_color)
                arr = pygame.surfarray.array2d(surf)
                self.failUnlessEqual(arr[0, 0], map_rgb(alpha_color),
                                     "%s != %s: bpp: %i" %
                                     (arr[0, 0],
                                      map_rgb(alpha_color),
                                      surf.get_bitsize()))
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_array3d(self):
        if not arraytype:
            self.fail("no array package installed")
        if arraytype == 'numeric':
            # This is known to fail with Numeric (wrong color element
            # values for 16 bit surfaces).
            return

        sources = [self._make_src_surface(16),
                   self._make_src_surface(16, srcalpha=True),
                   self._make_src_surface(24),
                   self._make_src_surface(32),
                   self._make_src_surface(32, srcalpha=True)]
        palette = self.test_palette

        for surf in sources:
            arr = pygame.surfarray.array3d(surf)
            map_rgb = surf.map_rgb
            unmap_rgb = surf.unmap_rgb
            def same_color(ac, sc):
                sc = unmap_rgb(map_rgb(sc))
                return (ac[0] == sc[0] and
                        ac[1] == sc[1] and
                        ac[2] == sc[2])
            for (x, y), i in self.test_points:
                self.failUnless(same_color(arr[x, y], palette[i]),
                                "%s != %s: flags: %i, bpp: %i, posn: %s" %
                                (tuple(arr[x, y]),
                                 unmap_rgb(map_rgb(palette[i])),
                                 surf.get_flags(), surf.get_bitsize(),
                                 (x, y)))
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_get_arraytype(self):
        if not arraytype:
            self.fail("no array package installed")

        self.failUnless((pygame.surfarray.get_arraytype() in
                         ['numpy', 'numeric']),
                        ("unknown array type %s" %
                         pygame.surfarray.get_arraytype()))
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_map_array(self):
        if not arraytype:
            self.fail("no array package installed")
        if not arraytype == 'numpy':
            # This test would probably fail for Numeric
            # (incompatible get_rgb and array element types
            #  and zero alpha for SRCALPHA surfaces).
            return

        arr3d = self._make_src_array3d(uint8)
        targets = [self._make_surface(16),
                   self._make_surface(16, srcalpha=True),
                   self._make_surface(24),
                   self._make_surface(32),
                   self._make_surface(32, srcalpha=True)]
        palette = self.test_palette

        for surf in targets:
            arr2d = pygame.surfarray.map_array(surf, arr3d)
            for (x, y), i in self.test_points:
                self.failUnlessEqual(arr2d[x, y], surf.map_rgb(palette[i]),
                                     "%i != %i, bitsize: %i, flags: %i" %
                                     (arr2d[x, y], surf.map_rgb(palette[i]),
                                      surf.get_bitsize(), surf.get_flags()))

        # Exception checks
        def do_map_array(surf, arr):
            pygame.surfarray.map_array(surf, arr)

        self.failUnlessRaises(ValueError, do_map_array,
                              self._make_surface(32),
                              self._make_array2d(uint8))
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_pixels2d(self):
        if not arraytype:
            self.fail("no array package installed")
        if arraytype == 'numeric':
            # This is known to fail with Numeric
            # (incompatible get_rgb and array element types).
            return

        sources = [self._make_surface(8),
                   self._make_surface(16, srcalpha=True),
                   self._make_surface(32, srcalpha=True)]

        for surf in sources:
            self.failIf(surf.get_locked())
            arr = pygame.surfarray.pixels2d(surf)
            self.failUnless(surf.get_locked())
            # Numpy uses the surface's buffer.
            if arraytype == "numeric":
                self.failUnlessEqual(surf.get_locks(), (ar,))
            self._fill_array2d(arr, surf)
            surf.unlock()
            self.failUnless(surf.get_locked())
            del arr
            self.failIf(surf.get_locked())
            self.failUnlessEqual(surf.get_locks(), ())
            self._assert_surface(surf)

        # Error checks
        def do_pixels2d(surf):
            pygame.surfarray.pixels2d(surf)

        self.failUnlessRaises(ValueError,
                              do_pixels2d,
                              self._make_surface(24))
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_use_arraytype(self):
        if not arraytype:
            self.fail("no array package installed")

        def do_use_arraytype(atype):
            pygame.surfarray.use_arraytype(atype)

        try:
            import numpy
        except ImportError:
            self.failUnlessRaises(ValueError, do_use_arraytype, 'numpy')
            self.failIfEqual(pygame.surfarray.get_arraytype(), 'numpy')
        else:
            pygame.surfarray.use_arraytype('numpy')
            self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numpy')

        try:
            import Numeric
        except ImportError:
            self.failUnlessRaises(ValueError, do_use_arraytype, 'numeric')
            self.failIfEqual(pygame.surfarray.get_arraytype(), 'numeric')
        else:
            pygame.surfarray.use_arraytype('numeric')
            self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numeric')

        self.failUnlessRaises(ValueError, do_use_arraytype, 'not an option')
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_array_alpha(self):
        if not arraytype:
            self.fail("no array package installed")

        palette = [(0, 0, 0, 0),
                   (10, 50, 100, 255),
                   (60, 120, 240, 130),
                   (64, 128, 255, 0),
                   (255, 128, 0, 65)]
        targets = [self._make_src_surface(8, palette=palette),
                   self._make_src_surface(16, palette=palette),
                   self._make_src_surface(16, palette=palette, srcalpha=True),
                   self._make_src_surface(24, palette=palette),
                   self._make_src_surface(32, palette=palette),
                   self._make_src_surface(32, palette=palette, srcalpha=True)]

        for surf in targets:
            p = palette
            if surf.get_bitsize() == 16:
                p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
            arr = pygame.surfarray.array_alpha(surf)
            if surf.get_masks()[3]:
                for (x, y), i in self.test_points:
                    self.failUnlessEqual(arr[x, y], p[i][3],
                                         ("%i != %i, posn: (%i, %i), "
                                          "bitsize: %i" %
                                          (arr[x, y], p[i][3],
                                           x, y,
                                           surf.get_bitsize())))
            else:
                self.failUnless(alltrue(arr == 255))

        # No per-pixel alpha when blanket alpha is None.
        for surf in targets:
            blacket_alpha = surf.get_alpha()
            surf.set_alpha(None)
            arr = pygame.surfarray.array_alpha(surf)
            self.failUnless(alltrue(arr == 255),
                            "bitsize: %i, flags: %i" %
                            (surf.get_bitsize(), surf.get_flags()))
            surf.set_alpha(blacket_alpha)

        # Bug for per-pixel alpha surface when blanket alpha 0.
        for surf in targets:
            blanket_alpha = surf.get_alpha()
            surf.set_alpha(0)
            arr = pygame.surfarray.array_alpha(surf)
            if surf.get_masks()[3]:
                self.failIf(alltrue(arr == 255),
                            "bitsize: %i, flags: %i" %
                            (surf.get_bitsize(), surf.get_flags()))
            else:
                self.failUnless(alltrue(arr == 255),
                                "bitsize: %i, flags: %i" %
                                (surf.get_bitsize(), surf.get_flags()))
            surf.set_alpha(blanket_alpha)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_pixels_alpha(self):
        if not arraytype:
            self.fail("no array package installed")

        palette = [(0, 0, 0, 0),
                   (127, 127, 127, 0),
                   (127, 127, 127, 85),
                   (127, 127, 127, 170),
                   (127, 127, 127, 255)]
        alphas = [0, 45, 86, 99, 180]

        surf = self._make_src_surface(32, srcalpha=True, palette=palette)

        self.failIf(surf.get_locked())
        arr = pygame.surfarray.pixels_alpha(surf)
        self.failUnless(surf.get_locked())
        surf.unlock()
        self.failUnless(surf.get_locked())

        for (x, y), i in self.test_points:
            self.failUnlessEqual(arr[x, y], palette[i][3])

        for (x, y), i in self.test_points:
            alpha = alphas[i]
            arr[x, y] = alpha
            color = (127, 127, 127, alpha)
            self.failUnlessEqual(surf.get_at((x, y)), color,
                                 "posn: (%i, %i)" % (x, y))

        del arr
        self.failIf(surf.get_locked())
        self.failUnlessEqual(surf.get_locks(), ())

        # Check exceptions.
        def do_pixels_alpha(surf):
            pygame.surfarray.pixels_alpha(surf)

        targets = [(8, False),
                   (16, False),
                   (16, True),
                   (24, False),
                   (32, False)]

        for bitsize, srcalpha in targets:
            self.failUnlessRaises(ValueError, do_pixels_alpha,
                                  self._make_surface(bitsize, srcalpha))
项目:ClassiPi    作者:mugroma3    | 项目源码 | 文件源码
def main():

  # Load the Inception model so it is ready for classifying images.
  try:
    model = inception.Inception()
  except FileNotFoundError:
    print ('###### warning ######')
    print ('this script requires inception.maybe_download() executed at least once, running it now')
    inception.maybe_download()
    model = inception.Inception()
  while True:
    try:
      start_time_camera = time.time()

      cam.start() 
      # start and stop prevent the buffer from filling up with more useless frames
      img = cam.get_image()
      cam.stop()
      image = pygame.surfarray.array3d(img)
      image = np.rot90(image, 3)
      end_time_camera = time.time()

      start_time = time.time()
      print ("Classifying image from camera...")
      with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        classify(model=model, image=image)
      end_time = time.time()
      time_dif_camera = end_time_camera - start_time_camera
      time_dif = end_time - start_time

      # Print the time-usage.
      print ('###### time usage camera ######')
      print(str(timedelta(seconds=int(round(time_dif_camera)))))
      print ('###### time usage NN ######')
      print(str(timedelta(seconds=int(round(time_dif)))))

      # Save the image that was just classified (for debug)
      im = Image.fromarray(image) 
      im.save(image_path)
    except (KeyboardInterrupt, SystemExit, RuntimeError, SystemError):
      cam.stop()
      model.close()
项目:ClassiPi    作者:mugroma3    | 项目源码 | 文件源码
def main():

  # Load the Inception model so it is ready for classifying images.
  try:
    model = inception.Inception()
  except FileNotFoundError:
    print ('###### warning ######')
    print ('this script requires inception.maybe_download() executed at least once, running it now')
    inception.maybe_download()
    model = inception.Inception()
  while True:
    try:
      start_time_camera = time.time()

      # multiple times to empty the buffer
      img = cam.get_image()
      img = cam.get_image()
      img = cam.get_image()

      image = pygame.surfarray.array3d(img)
      image = np.fliplr(np.rot90(image, 3))

      if debug: 
            # Save the image that was just classified (for debug)
            im = Image.fromarray(image) 
            im.save(image_path)

      end_time_camera = time.time()

      start_time = time.time()
      #print ("Classifying image from camera...")
      with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        classify(model=model, image=image)
      end_time = time.time()
      time_dif_camera = end_time_camera - start_time_camera
      time_dif = end_time - start_time

      # Print the time-usage.
      out_file.write('###### time usage camera ######\n')
      out_file.write(str(timedelta(seconds=int(round(time_dif_camera))))+"\n")
      out_file.write('###### time usage NN ######\n')
      out_file.write(str(timedelta(seconds=int(round(time_dif))))+"\n")
      out_file.flush()
      os.fsync(out_file)
      print('###### time usage camera ######')
      print(str(timedelta(seconds=int(round(time_dif_camera)))))
      print('###### time usage NN ######')
      print(str(timedelta(seconds=int(round(time_dif)))))


    except (KeyboardInterrupt, SystemExit, RuntimeError, SystemError):
      cam.stop()
      model.close()
      out_file.close()
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_array_alpha(self):
        if not arraytype:
            self.fail("no array package installed")
        if arraytype == 'numeric':
            # This is known to fail with Numeric (differing values for
            # get_rgb and array element for 16 bit surfaces).
            return

        palette = [(0, 0, 0, 0),
                   (10, 50, 100, 255),
                   (60, 120, 240, 130),
                   (64, 128, 255, 0),
                   (255, 128, 0, 65)]
        targets = [self._make_src_surface(8, palette=palette),
                   self._make_src_surface(16, palette=palette),
                   self._make_src_surface(16, palette=palette, srcalpha=True),
                   self._make_src_surface(24, palette=palette),
                   self._make_src_surface(32, palette=palette),
                   self._make_src_surface(32, palette=palette, srcalpha=True)]

        for surf in targets:
            p = palette
            if surf.get_bitsize() == 16:
                p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
            arr = pygame.surfarray.array_alpha(surf)
            if surf.get_masks()[3]:
                for (x, y), i in self.test_points:
                    self.failUnlessEqual(arr[x, y], p[i][3],
                                         ("%i != %i, posn: (%i, %i), "
                                          "bitsize: %i" %
                                          (arr[x, y], p[i][3],
                                           x, y,
                                           surf.get_bitsize())))
            else:
                self.failUnless(alltrue(arr == 255))

        # No per-pixel alpha when blanket alpha is None.
        for surf in targets:
            blacket_alpha = surf.get_alpha()
            surf.set_alpha(None)
            arr = pygame.surfarray.array_alpha(surf)
            self.failUnless(alltrue(arr == 255),
                            "bitsize: %i, flags: %i" %
                            (surf.get_bitsize(), surf.get_flags()))
            surf.set_alpha(blacket_alpha)

        # Bug for per-pixel alpha surface when blanket alpha 0.
        for surf in targets:
            blanket_alpha = surf.get_alpha()
            surf.set_alpha(0)
            arr = pygame.surfarray.array_alpha(surf)
            if surf.get_masks()[3]:
                self.failIf(alltrue(arr == 255),
                            "bitsize: %i, flags: %i" %
                            (surf.get_bitsize(), surf.get_flags()))
            else:
                self.failUnless(alltrue(arr == 255),
                                "bitsize: %i, flags: %i" %
                                (surf.get_bitsize(), surf.get_flags()))
            surf.set_alpha(blanket_alpha)
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_pixels_alpha(self):
        if not arraytype:
            self.fail("no array package installed")

        palette = [(0, 0, 0, 0),
                   (127, 127, 127, 0),
                   (127, 127, 127, 85),
                   (127, 127, 127, 170),
                   (127, 127, 127, 255)]
        alphas = [0, 45, 86, 99, 180]

        surf = self._make_src_surface(32, srcalpha=True, palette=palette)

        self.failIf(surf.get_locked())
        arr = pygame.surfarray.pixels_alpha(surf)
        self.failUnless(surf.get_locked())
        # Numpy uses the surface's buffer.
        if arraytype == 'numeric':
            self.failUnlessEqual(surf.get_locks(), (arr,))
        surf.unlock()
        self.failUnless(surf.get_locked())

        for (x, y), i in self.test_points:
            self.failUnlessEqual(arr[x, y], palette[i][3])

        for (x, y), i in self.test_points:
            alpha = alphas[i]
            arr[x, y] = alpha
            color = (127, 127, 127, alpha)
            self.failUnlessEqual(surf.get_at((x, y)), color,
                                 "posn: (%i, %i)" % (x, y))

        del arr
        self.failIf(surf.get_locked())
        self.failUnlessEqual(surf.get_locks(), ())

        # Check exceptions.
        def do_pixels_alpha(surf):
            pygame.surfarray.pixels_alpha(surf)

        targets = [(8, False),
                   (16, False),
                   (16, True),
                   (24, False),
                   (32, False)]

        for bitsize, srcalpha in targets:
            self.failUnlessRaises(ValueError, do_pixels_alpha,
                                  self._make_surface(bitsize, srcalpha))