コード例 #1
0
ファイル: frame.py プロジェクト: olpa/tex
    def setType(self, type):

        #Delete old panels
        for i in self.GetChildren():
            if i.GetName() in ["imagePanel", "customPanel", "colorPanel", "rotationPanel", "textPanel", "vartextPanel"]:
                i.Destroy()

        if type == "color":
            self.color = color(self)
            self.customSizer.Add(self.color, 1, wx.EXPAND|wx.ALL, 4)
        if type == "image":
            self.image = image(self)
            self.customSizer.Add(self.image, 1, wx.EXPAND|wx.ALL, 4)
        if type == "text":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND|wx.ALL, 4)
            self.text = text(self)
            self.customSizer.Add(self.text, 1, wx.EXPAND|wx.ALL, 4)
        if type == "vartext":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND|wx.ALL, 4)
            self.vartext = vartext(self)
            self.customSizer.Add(self.vartext, 1, wx.EXPAND|wx.ALL, 4)

        self.SetSizerAndFit(self.sizer)

        self.Layout()
        self.parent.Layout()
        self.parent.propertiesPanel.Layout()
コード例 #2
0
    def setType(self, type):

        #Delete old panels
        for i in self.GetChildren():
            if i.GetName() in [
                    "imagePanel", "customPanel", "colorPanel", "rotationPanel",
                    "textPanel", "vartextPanel"
            ]:
                i.Destroy()

        if type == "color":
            self.color = color(self)
            self.customSizer.Add(self.color, 1, wx.EXPAND | wx.ALL, 4)
        if type == "image":
            self.image = image(self)
            self.customSizer.Add(self.image, 1, wx.EXPAND | wx.ALL, 4)
        if type == "text":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND | wx.ALL, 4)
            self.text = text(self)
            self.customSizer.Add(self.text, 1, wx.EXPAND | wx.ALL, 4)
        if type == "vartext":
            self.rotation = rotation(self)
            self.customSizer.Add(self.rotation, 0, wx.EXPAND | wx.ALL, 4)
            self.vartext = vartext(self)
            self.customSizer.Add(self.vartext, 1, wx.EXPAND | wx.ALL, 4)

        self.SetSizerAndFit(self.sizer)

        self.Layout()
        self.parent.Layout()
        self.parent.propertiesPanel.Layout()
コード例 #3
0
ファイル: great_circle.py プロジェクト: nfcd/compGeo
def great_circle(strike, dip):
    '''
	great_circle computes the great circle path of a plane in spherical coordinate system

	pole_trd, pole_plg - pole of the plane

	Python function translated from the Matlab function
	GreatCircle in Allmendinger et al. (2012)
	'''
    pole_trd, pole_plg = pole_from_plane(strike, dip)

    # This vector will trace great circle from South to North pole
    v = np.array(sph_to_cart(strike, 0.0))

    n = 181  # number of angles from 0 to 180
    NED = np.zeros((3, n))

    # To make the great circle, rotate the North vector 180 degrees
    # in increments of 1 degree
    for i in range(0, n):
        rad = np.radians(i)
        R = rotation(pole_trd, pole_plg, rad)
        NED[:, i] = np.dot(R,
                           v)  # write result to ith column of the NED matrix

    # there could be vectors with negative plunge due to imprecise calcualtions
    # have a look at an example https://github.com/rzaitov/compGeo/blob/master/source/notebooks/Unstable_Rotate.ipynb
    mask = NED[2, :] < 0
    NED[2, mask] = 0

    return cart_to_sph(NED[0, :], NED[1, :], NED[2, :])
コード例 #4
0
ファイル: small_circle.py プロジェクト: nfcd/compGeo
def small_circle(axis_trd, axis_plg, cone_angle):
    '''
	small_circle computes the paths of a small circle defined
	by its axis and cone angle

	axis_trd = trend of axis
	axis_plg = plunge of axis
	cone_angle = cone angle

	Python function translated from the Matlab function
	SmallCircle in Allmendinger et al. (2012)
	'''
    v = np.array(sph_to_cart(axis_trd,
                             axis_plg - cone_angle))  # vector to rotate

    # To make the small circle, rotate the starting line
    # 360 degrees in increments of 1 degree
    n = 361  # number of angles from 0 to 360
    NED = np.zeros((3, n))

    for i in range(n):
        rot = np.radians(i)
        R = rotation(axis_trd, axis_plg, rot)
        NED[:, i] = np.dot(R, v)

    # select vectors with non-negative plunge
    mask = NED[2, :] >= 0
    NED = NED[:, mask]

    return cart_to_sph(NED[0, :], NED[1, :], NED[2, :])
コード例 #5
0
ファイル: examples.py プロジェクト: zhanglae/pyray
def draw_oscillating_sphere(save_dir, number_of_circles, line_thickness):
    # Craete total 60 images
    for i in np.arange(60):
        # 2.5 is an angle of Z axis
        # pi * sin(k) is an oscillating factor
        r = rotation.rotation(
            3,
            2.5 + np.pi * np.sin(i / 10.0) * np.random.uniform(0.75, 1) / 20.0)
        # Create the canvas size of (500, 500)
        im = Image.new("RGB", (500, 500), (1, 1, 1))
        draw = ImageDraw.Draw(im, 'RGBA')
        # Sphere's center is np.array([0,0,0])
        # The vector that passes through the center is np.array([0,0,1])
        # Radius is oscillating randomly: 1 * np.random.uniform(0.75,1) + 0.4 * np.sin(np.pi/10.0*i)
        circle.draw_sphere(draw,
                           np.array([0, 0, 0]),
                           np.array([0, 0, 1]),
                           1 * np.random.uniform(0.75, 1) +
                           0.4 * np.sin(np.pi / 10.0 * i),
                           r,
                           num_circle=number_of_circles,
                           rgba=(182, 183, 186, 255),
                           width=line_thickness)
        file_name = save_dir + str(i) + '.png'
        im.save(file_name)
コード例 #6
0
ファイル: examples.py プロジェクト: zhanglae/pyray
def draw_wavy_sphere_acceleration_wrapper(save_dir, number_of_circles,
                                          line_thickness):
    # Create n images (frames) where n = number_of_circles
    for i in np.arange(number_of_circles):
        wavy_index = i % number_of_circles
        if (wavy_index > 0.65 * number_of_circles and wavy_index % 2 != 0):
            pass
        else:
            # 2.52 is an angle of Z axis (Why do I choose 2.52? For an aesthetic reason:))
            r = rotation.rotation(
                3, 2.50 +
                np.pi * np.sin(i / 10.0) * np.random.uniform(0.8, 1) / 30.0)
            # Create the canvas size of (500, 500)
            im = Image.new("RGB", (500, 500), (1, 1, 1))
            draw = ImageDraw.Draw(im, 'RGBA')
            # Sphere's center is np.array([0,0,0])
            # The vector that passes through the center is np.array([0,0,1])
            # Radius is oscillating randomly
            circle.draw_sphere2(draw,
                                np.array([0, 0, 0]),
                                np.array([0, 0, 1]),
                                1,
                                r,
                                wavy_index=wavy_index,
                                num_circle=number_of_circles,
                                rgba=(182, 183, 186, 255),
                                width=line_thickness)
            file_name = save_dir + str(i) + '.png'
            im.save(file_name)
コード例 #7
0
ファイル: tests.py プロジェクト: undu/pyray
 def test_rotation_360(self):
     """
     Rotating by 360 degrees should preserve the vector.
     """
     r = rotation(3, np.pi * 2)
     vec = np.random.uniform(size=3)
     vec_rot = np.dot(r, vec)
     self.assertTrue(sum(abs(vec - vec_rot) / vec) < 1e-5)
コード例 #8
0
ファイル: examples.py プロジェクト: luzpaz/pyray
def draw_rotating_sphere(save_dir, number_of_circles, line_thickness):
    # Craete total 30 images
    for i in np.arange(30):
        # We'll rotate the sphere by 18 degrees (18 = pi/10) 
        r = rotation.rotation(3, np.pi*i / 100.0)
        # Create the canvas size of (500, 500)
        im = Image.new("RGB", (500, 500), (1, 1, 1))
        draw = ImageDraw.Draw(im, 'RGBA')
        circle.draw_sphere(draw, np.array([0,0,0]), np.array([0,0,1]), 1, r, num_circle = number_of_circles, rgba=(182, 183, 186, 255), width = line_thickness)
        # Save
        file_name = save_dir + str(i) + '.png'
        im.save(file_name)
コード例 #9
0
ファイル: polyhedron.py プロジェクト: undu/pyray
def draw_tetartoid(basedir=".\\"):
    """
    @MoneyShot
    Draws out a Tetartoid.
    args:
        basedir:The directory where the images are to be saved. 
            In the main pyray repo, basedir is ..\\images\\RotatingCube\\
    """
    for i in range(0, 31):
        im = Image.new("RGB", (2048, 2048), (1, 1, 1))
        draw = ImageDraw.Draw(im, 'RGBA')
        r = np.transpose(rotation(3, np.pi * (9 + i) / 15))  #i=9
        tetartoid(draw, r, t=0.1)
        im.save(basedir + "im" + str(i) + ".png")
コード例 #10
0
ファイル: polyhedron.py プロジェクト: undu/pyray
def platonic_solids(basedir=".\\"):
    """
    @MoneyShot
    Draws out an Icosahedron and Dodecahedron.
    args:
        basedir:The directory where the images are to be saved. 
            In the main pyray repo, basedir is ..\\images\\RotatingCube\\
    """
    for i in range(0, 31):
        im = Image.new("RGB", (2048, 2048), (1, 1, 1))
        draw = ImageDraw.Draw(im, 'RGBA')
        r = np.transpose(rotation(3, np.pi * (9 + i) / 15))  #i=9
        #dodecahedron(draw, r, shift = np.array([370, 1270, 0]), scale = 150)
        #icosahedron(draw, r, shift = np.array([1470, 1270, 0]), scale = 150)
        tetartoid(draw, r, t=0.1)
        im.save(basedir + "im" + str(i) + ".png")
コード例 #11
0
ファイル: LorentzTransform.py プロジェクト: sadhi003/PyPWA
 def __init__(self, a=1., b=1., g=1.):
     #sets beta, the velocity = p/E
     self.m = np.matrix(np.identity(4))
     if isinstance(a, FourVector):
         x = -a.x / a.E
         y = -a.y / a.E
         z = -a.z / a.E
         _beta = ThreeVector(x, y, z)
         self.setBeta(_beta)
     if type(a) == np.matrix:
         self.m = a
     elif type(a) == float:  #alpha beta and gamma should all be floats
         self.alpha = a
         self.beta = b
         self.gamma = g
         rot = rotation(self.alpha, self.beta, self.gamma)
         self.setrot(rot)
コード例 #12
0
ファイル: LorentzTransform.py プロジェクト: JTPond/PyPWA
 def __init__(self, a = 1., b = 1., g = 1.):
     #sets beta, the velocity = p/E
     self.m = np.matrix(np.identity(4))
     if isinstance(a, FourVector):
         x = -a.x / a.E
         y = -a.y / a.E
         z = -a.z / a.E
         _beta = ThreeVector(x, y, z)
         self.setBeta(_beta)
     if type(a) == np.matrix:
         self.m = a
     elif type(a) == float: #alpha beta and gamma should all be floats
         self.alpha = a
         self.beta = b
         self.gamma = g
         rot = rotation(self.alpha, self.beta, self.gamma)
         self.setrot(rot)
コード例 #13
0
ファイル: cube.py プロジェクト: undu/pyray
 def plot_faces(self, r=None, j=0, body_indice=None):
     """
     Plots all the 2d faces of the hypercube.
     """
     if r is None:
         r = rotation(self.dim)
     im = Image.new("RGB", (2048, 2048), "black")
     draw = ImageDraw.Draw(im, 'RGBA')
     for f in self.faces:
         f.plot(r, draw, (255, 55, 0, 22))
     for edge in self.edges:
         edge.plot(r, draw, (255, 131, 0))
     if body_indice is not None:
         indx = 0
         for bi in body_indice:
             j = j + bi * 10**indx + 1
             body = self.bodies[bi]
             body.plot(r, draw, colors[bi])
             indx = indx + 1
     im.save('Images\\RotatingCube\\im' + str(j) + '.png')
コード例 #14
0
ファイル: cube.py プロジェクト: undu/pyray
 def plot_edges2(self,
                 draw,
                 r=None,
                 seq=False,
                 offset=None,
                 fill=(255, 165, 5),
                 scale=500,
                 shift=np.array([1000, 1000, 0, 0])):
     """
     Same as plot_edges, but allows for an offset.
     """
     if offset is None:
         offset = np.zeros(self.dim)
     if r is None:
         r = rotation(self.dim)
     if seq:
         self.generate_sequential_edges()
         edges = self.sequential_edges
     else:
         edges = self.edges
     for edge in edges:
         if edge.vertice1.index == 0:
             [v1, v2] = [
                 np.dot(r, edge.vertice1.binary + offset),
                 np.dot(r, edge.vertice2.binary + offset)
             ]
         elif edge.vertice2.index == 2**(self.dim) - 1:
             [v1, v2] = [
                 np.dot(r, edge.vertice1.binary - offset),
                 np.dot(r, edge.vertice2.binary - offset)
             ]
         else:
             [v1, v2] = [
                 np.dot(r, edge.vertice1.binary),
                 np.dot(r, edge.vertice2.binary)
             ]
         [v1x, v1y] = (shift[:self.dim] + scale * v1)[0:2]
         [v2x, v2y] = (shift[:self.dim] + scale * v2)[0:2]
         draw.line((v1x, v1y, v2x, v2y), fill=fill, width=4)
コード例 #15
0
ファイル: cube.py プロジェクト: undu/pyray
 def plot_edges(self, r=None, seq=False, j=0):
     """
     Plots all the edges of the hypercube.
     """
     if r is None:
         r = rotation(self.dim)
     im = Image.new("RGB", (2048, 2048), (1, 1, 1))
     draw = ImageDraw.Draw(im, 'RGBA')
     if seq:
         self.generate_sequential_edges()
         edges = self.sequential_edges
     else:
         edges = self.edges
     for edge in edges:
         [v1, v2] = [
             np.dot(r, edge.vertice1.binary),
             np.dot(r, edge.vertice2.binary)
         ]
         [v1x, v1y] = (shift[:self.dim] + scale * v1)[0:2]
         [v2x, v2y] = (shift[:self.dim] + scale * v2)[0:2]
         draw.line((v1x, v1y, v2x, v2y), fill=(255, 165, 0), width=2)
     return [im, draw]
コード例 #16
0
ファイル: cube.py プロジェクト: undu/pyray
def cube_with_cuttingplanes(numTerms,
                            im_ind=0,
                            pos=[300, 700, 0],
                            draw1=None,
                            scale=100,
                            popup=False,
                            baseLocn='.\\im'):
    """
    @MoneyShot
    Generates larger and larger cubes showing their cutting planes
    representing polynomial terms.
    args:
        numTerms: The number of values each dimension can take.
        im_ind: The index of the image in the video
                (will affect file name of dumped image).
        pos: The position on the image where the leftmost edge of the cube
             should be.
        draw1: The draw object of the image. If not provided,
               new images are created.
    """
    for j in range(30, 31):
        if draw1 is None:
            im = Image.new("RGB", (2048, 2048), "black")
            draw = ImageDraw.Draw(im, 'RGBA')
        else:
            draw = draw1
        r = rotation(3, j / 80.0 * np.pi * 2)
        # Vertices
        vertices = [general_base(i, numTerms, 3) for i in range(numTerms**3)]
        rotated_vertices = (
            np.transpose(np.dot(r, np.transpose(vertices))) * scale + pos)
        # Draw edges.
        for i in range(len(vertices)):
            for dim in range(3):
                if (vertices[i][dim] < (numTerms - 1)
                        and i + numTerms**dim <= len(vertices) - 1):
                    v1 = rotated_vertices[i]
                    v2 = rotated_vertices[i + numTerms**dim]
                    draw.line((v1[0], v1[1], v2[0], v2[1]),
                              fill="yellow",
                              width=2)
        for v in rotated_vertices:
            draw.ellipse((v[0] - 5, v[1] - 5, v[0] + 5, v[1] + 5),
                         fill='red',
                         outline='red')
        for power in range(1, (numTerms - 1) * 3):
            rgb = colors[(power - 1) % 14]
            rgba = colors[(power - 1) % 14] + (100, )
            sqr1 = rotated_vertices[np.array(range(len(vertices)))[np.array(
                [sum(i) == power for i in vertices])]]
            hull = ConvexHull([i[:2] for i in sqr1]).vertices
            poly = [(sqr1[i][0], sqr1[i][1]) for i in hull]
            draw.polygon(poly, rgba)
            for vv in sqr1:
                [vx, vy] = vv[:2]
                draw.ellipse((vx - 11, vy - 11, vx + 11, vy + 11),
                             fill=rgb,
                             outline=rgb)
        if draw1 is None:
            if popup:
                im.show()
            im.save(baseLocn + str(im_ind) + '.png')
コード例 #17
0
#! /usr/bin/env python
# -*- coding:utf8-*-

import managerPlateau
import rotation
import alignement
from random import randint
if __name__ == "__main__":
    plateauT = managerPlateau.initPlateau(6)
    managerPlateau.affichplateau(plateauT)
    alignement.ensemble(6, plateauT, 5, 1)
    rotation.rotation(6, plateauT, 3, True)
    managerPlateau.affichplateau(plateauT)
コード例 #18
0
def treatment(num_animals, n_pastures, pasture_size_ha, outdir):
    """Run "smart" rotation."""
    
    forage_args = default_forage_args()
    rotation.rotation(forage_args, n_pastures, pasture_size_ha, num_animals,
                      outdir)
コード例 #19
0
 c2 = int(
     input(
         "\nEnter 1 for clockwise rotation\nEnter 2 for anticlockwise rotation\n\nINPUT : "
     ))
 if (c2 == 1):
     theta = float(input("\nEnter the angle of clockwise rotation: "))
     x_fixed = float(
         input(
             "Enter the abscissa of the pivot point(Enter 0 in case of origin): "
         ))
     y_fixed = float(
         input(
             "Enter the ordinate of the pivot point(Enter 0 in case of origin): "
         ))
     temp_list = mm.matrix_mul(
         rot.rotation(c2, x_fixed, y_fixed, theta), temp_list)
 elif (c2 == 2):
     theta = float(
         input("\nEnter the angle of anticlockwise rotation: "))
     x_fixed = float(
         input(
             "Enter the abscissa of the pivot point(Enter 0 in case of origin): "
         ))
     y_fixed = float(
         input(
             "Enter the ordinate of the pivot point(Enter 0 in case of origin): "
         ))
     temp_list = mm.matrix_mul(
         rot.rotation(c2, x_fixed, y_fixed, theta), temp_list)
 else:
     print("\nWrong choice. Please enter correct details.")
コード例 #20
0
    def __init__(self):
        # Manually set up our ROI for grabbing the hand.
        # Feel free to change these. I just chose the top right corner for filming.
        roi_top = 20
        roi_bottom = 140
        roi_right = 260
        roi_left = 380

        # ROI 2
        roi_top2 = 340
        roi_bottom2 = 460

        cam = cv2.VideoCapture(0)
        cam.set(3, 640)
        cam.set(4, 480)
        # Intialize a frame count
        num_frames = 0
        # background calc in real time
        # Start with a halfway point between 0 and 1 of accumulated weight
        accumulated_weight = 0.7
        accumulated_weight2 = 0.7
        accumulated_weight3 = 0.7
        background_calc = calc_accum()

        while True:
            # get the current frame
            ret, frame = cam.read()
            # flip the frame so that it is not the mirror view
            frame = cv2.flip(frame, 1)
            # clone the frame
            frame_copy = frame.copy()

            # object detection.
            height = frame_copy.shape[0]
            object_roi_top = height / 2
            object_roi_bottom = 640
            object_detect = frame[object_roi_top:object_roi_bottom, :]
            object_gray = cv2.cvtColor(object_detect, cv2.COLOR_BGR2GRAY)
            object_gray = cv2.GaussianBlur(object_gray, (5, 5), 0)

            # ROI 1
            # Grab the ROI from the frame(1)
            roi = frame[roi_top:roi_bottom, roi_right:roi_left]
            gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
            # Apply grayscale and blur to ROI
            gray = cv2.GaussianBlur(gray, (5, 5), 0)

            # ROI 2
            roi2 = frame[roi_top2:roi_bottom2, roi_right:roi_left]
            gray2 = cv2.cvtColor(roi2, cv2.COLOR_BGR2GRAY)
            gray2 = cv2.GaussianBlur(gray2, (5, 5), 0)

            # For the first 60 frames we will calculate the average of the background.
            if num_frames < 60:
                background_calc.calc_accum_avg(gray, accumulated_weight)
                background_calc.calc_accum_avg2(gray2, accumulated_weight2)
                background_calc.calc_accum_avg3(object_gray,
                                                accumulated_weight3)
                if num_frames <= 59:
                    cv2.putText(frame_copy, "WAIT! GETTING BACKGROUND AVG.",
                                (1, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                    cv2.imshow("Vision", frame_copy)
            else:

                # shape detect upper
                upper_shape = segment(gray)
                if upper_shape is not None:
                    upper_thresh, upper_contour, upper_segment, upper_cnts = upper_shape
                    upper_shape_detect = detect(upper_contour)
                    # Apply hough transform on the image
                    (upper_cX, upper_cY, upper_c) = centroid(upper_cnts)

                    cv2.drawContours(frame_copy,
                                     [upper_segment + (roi_right, roi_top)],
                                     -1, (255, 0, 0), 1)
                    cv2.circle(frame_copy,
                               (upper_cX + roi_right, roi_top + upper_cY), 7,
                               (255, 0, 0), -1)
                    cv2.putText(frame_copy,
                                "upper_shape : " + str(upper_shape_detect),
                                (1, 440), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)

                    cv2.imshow("upper_threshold", upper_thresh)
                    # shape detect bottom
                bottom_shape = segment(gray2)
                if bottom_shape is not None:
                    bottom_thresh, bottom_contour, bottom_segment, bottom_cnts = bottom_shape
                    bottom_shape_detect = detect(bottom_contour)
                    (bottom_cX, bottom_cY, bottom_c) = centroid(bottom_cnts)

                    cv2.drawContours(frame_copy,
                                     [bottom_segment + (roi_right, roi_top2)],
                                     -1, (255, 0, 0), 1)
                    cv2.putText(frame_copy,
                                "bottom_shape : " + str(bottom_shape_detect),
                                (1, 460), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                    cv2.circle(frame_copy,
                               (bottom_cX + roi_right, roi_top2 + bottom_cY),
                               7, (255, 0, 0), -1)
                    cv2.imshow("bottom_threshold", bottom_thresh)

                # distance
                upper_c = (upper_cX + roi_right, roi_top + upper_cY)
                bottom_c = (bottom_cX + roi_right, roi_top2 + bottom_cY)
                roi_distance = distance(upper_c, bottom_c)
                cv2.putText(frame_copy,
                            "ROI DISTANCE={} ".format(roi_distance), (1, 400),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

                if upper_shape_detect == "square" or "rectangle" and bottom_shape_detect == "square" or "rectangle":
                    angles = rotation(bottom_c, upper_c)
                    cv2.putText(frame_copy, "difference ={}".format(angles),
                                (1, 420), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                (0, 0, 255), 1)
                object_detect = segment(object_gray)
                if object_detect is not None:
                    object_thresh, object_contour, object_segment, object_cnts = object_detect
                    multi_obejct_detect = multi_detect()
                    multi_obejct_detect.detect(
                        frame_copy[object_roi_top:object_roi_bottom, :],
                        object_contour)

    # Draw ROI Rectangle on frame copy
            cv2.rectangle(frame_copy, (roi_left, roi_top),
                          (roi_right, roi_bottom), (0, 0, 255), 5)
            cv2.rectangle(frame_copy, (roi_left, roi_top2),
                          (roi_right, roi_bottom2), (0, 0, 255), 5)

            # increment the number of frames for tracking
            num_frames += 1
            #print(distance(upper_c,bottom_c))

            # Display the frame with segmented hand
            cv2.imshow("Vision", frame_copy)

            # Close windows with Esc
            k = cv2.waitKey(1) & 0xFF

            if k == 27:
                break
        cam.release()
        cv2.destroyAllWindows()
コード例 #21
0
ファイル: cube.py プロジェクト: undu/pyray
def teserract_body_diagonal2(im_ind=70,
                             width=15,
                             scale=500,
                             shift1=np.array([1000, 1000, 0, 0, 0]),
                             move=0.0):
    '''
    @MoneyShot
    Draws a four dimensional teserract with two tetrahedral and one
    octahedral planes visible.
    '''
    c1 = Cube(4)
    r = np.eye(4)
    r[:3, :3] = rotation(3, np.pi * 2 * (27.0 - im_ind) / 80.0)
    newr = general_rotation(np.array(
        [1, -1, 0]), (np.pi / 2 + np.arccos(np.sqrt(0.666666))) * 4.35 / 10.0)
    oldr = rotation(3, np.pi * 2 * (27.0) / 80.0)
    r[:3, :3] = oldr
    im = Image.new("RGB", (2048, 2048), (1, 1, 1))
    draw = ImageDraw.Draw(im, 'RGBA')
    rotated_vertices = np.transpose(np.dot(r, np.transpose(
        c1.vertice_matrix))) * scale + shift1[:4]
    body_diag = (c1.vertices[0].to_binary() - c1.vertices[15].to_binary())
    frst = [1, 2, 4]
    scnd = [3, 5, 6]
    for e in c1.edges:
        if e.vertice1.index == 0 and e.vertice2.index in frst:
            pt1 = rotated_vertices[e.vertice1.index]
            pt2 = rotated_vertices[e.vertice2.index]
            center = (pt1 + pt2) / 2.0
            p = im_ind / 10.0
            pp1 = (1 - p) * pt1 + p * pt2
            p = p + 0.08
            pp2 = (1 - p) * pt1 + p * pt2
            draw.line((pp1[0], pp1[1], pp2[0], pp2[1]),
                      fill=(200, 220, 5),
                      width=10)
    tri = []
    for j in frst:
        tri.append((rotated_vertices[j][0], rotated_vertices[j][1]))
    sqr1 = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 3]
    ]] + (rotated_vertices[0] - rotated_vertices[15]) * -move
    sqr1_orig = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 3]
    ]]
    draw.polygon(jarvis_convex_hull(sqr1), (255, 0, 0, int(65)))
    i = 0
    a = list(range(4))
    a.pop(i)
    tri = []
    tri_orig = []
    for j in a:
        tri.append((sqr1[j][0], sqr1[j][1]))
        tri_orig.append((sqr1_orig[j][0], sqr1_orig[j][1]))
    for ver in c1.vertices[c1.vertice_coordinate_sums == 3]:
        ver.plot(r,
                 draw, (255, 0, 0),
                 10,
                 offset=-body_diag * move,
                 scale=scale,
                 shift=shift1)
        for ver1 in c1.vertices[c1.vertice_coordinate_sums == 3]:
            e = Edge(ver, ver1)
            e.plot(r,
                   draw, (255, 0, 0),
                   width=2,
                   offset=-body_diag * move,
                   scale=scale,
                   shift=shift1)
    hexag = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 2]
    ]]
    for ed in [(5, 3), (5, 6), (5, 9), (5, 12), (10, 3), (10, 6), (10, 9),
               (10, 12), (3, 6), (3, 9), (12, 6), (12, 9)]:
        v1 = rotated_vertices[ed[0]]
        v2 = rotated_vertices[ed[1]]
        draw.line((v1[0], v1[1], v2[0], v2[1]), fill=(0, 255, 0), width=4)
        #draw.line((v1[0], v1[1], v2[0], v2[1]), fill = (255-im_ind*10,165+im_ind,0), width=4)
    for ver in c1.vertices[c1.vertice_coordinate_sums == 2]:
        ver.plot(r, draw, (0, 255, 0), 10, scale=scale, shift=shift1)
        #ver.plot(r, draw, (255-im_ind*25,im_ind*25,0), 10, scale=scale1, shift=shift1)
    draw.polygon(jarvis_convex_hull(hexag), (0, 255, 0, int(65)))
    for ver in c1.vertices[c1.vertice_coordinate_sums == 1]:
        #ver.plot(r, draw, (0,0,255), 10, offset = body_diag * move)
        ver.plot(r,
                 draw, (255, 0, 0),
                 10,
                 offset=body_diag * move,
                 scale=scale,
                 shift=shift1)
        #ver.plot(r, draw, (0,0,255), 10)
        for ver1 in c1.vertices[c1.vertice_coordinate_sums == 1]:
            e = Edge(ver, ver1)
            e.plot(r,
                   draw, (0, 0, 255),
                   offset=body_diag * move,
                   scale=scale,
                   shift=shift1)
            #e.plot(r,draw,(255-im_ind*16,165-im_ind*13,im_ind*25), offset = body_diag * move,scale=scale1, shift=shift1)
    sqr2 = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 1]
    ]] + (rotated_vertices[0] - rotated_vertices[15]) * move
    sqr2_orig = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 1]
    ]]
    draw.polygon(jarvis_convex_hull(sqr2), (0, 0, 255, int(65)))
    i = 3
    a = list(range(4))
    a.pop(i)
    tri = []
    tri_orig = []
    for j in a:
        tri.append((sqr2[j][0], sqr2[j][1]))
        tri_orig.append((sqr2_orig[j][0], sqr2_orig[j][1]))
    v1 = rotated_vertices[0]
    v2 = rotated_vertices[15]
    im.save('Images\\RotatingCube\\im' + str(im_ind) + '.png')
コード例 #22
0
print("%s seconds" % (time.time() - start_time))

count = 0

while count < num_proj:
    count += 1
    nnx = np.random.uniform(0, 10)
    nny = np.random.uniform(0, 10)
    nnz = np.random.uniform(0, 10)
    theta = np.random.uniform(0, 2 * np.pi)

    nx = 1 / np.sqrt(nnx**2 + nny**2 + nnz**2) * nnx
    ny = 1 / np.sqrt(nnx**2 + nny**2 + nnz**2) * nny
    nz = 1 / np.sqrt(nnx**2 + nny**2 + nnz**2) * nnz

    R = rotation(nx, ny, nz, theta)

    subcat['Position'] = da.transpose(
        da.dot(R, da.transpose(subcat['Position'])))

    mesh = subcat.to_mesh(Nmesh=nmesh, BoxSize=bs)

    proj1 = np.fft.fftshift(mesh.preview(axes=[0, 1], Nmesh=nmesh))
    proj2 = np.fft.fftshift(mesh.preview(axes=[0, 2], Nmesh=nmesh))
    proj3 = np.fft.fftshift(mesh.preview(axes=[1, 2], Nmesh=nmesh))

    np.save(
        '/n/dvorkin_lab/anadr/%s_proj/%s/hbugfix/%s_%s_projxy_%s_%s' %
        (name, numb, name, numb, count, item), proj1)
    np.save(
        '/n/dvorkin_lab/anadr/%s_proj/%s/hbugfix/%s_%s_projxz_%s_%s' %
コード例 #23
0
def update_view(angle, data ):
    """Updates the view of a sample.
    Takes the angle (an int, from 0 to 359) and the list of four bytes of data in the order they arrived.
"""
    global offset, scan
    # unpack data using the denomination used during the discussions
    x = data[0]
    x1= data[1]
    x2= data[2]
    x3= data[3]
    
    angle_rad = angle * math.pi / 180.0
    c = math.cos(angle_rad)
    s = -math.sin(angle_rad)

    dist_mm = x | (( x1 & 0x3f) << 8) # distance is coded on 13 bits ? 14 bits ?
    quality = x2 | (x3 << 8) # quality is on 16 bits
    lidarData[angle] = [dist_mm,quality]

    # Modified for 3D vectors
    raw_dist_x = dist_mm*c
    raw_dist_y = dist_mm*s
    dist_x, dist_y, dist_z = rot.rotation(raw_dist_x, raw_dist_y, 0, yaw_angle, pitch_angle)
    dist_z = -dist_z
    if visualization:
        #reset the point display
        point.pos[angle+(360*loc)] = vector( 0, 0, 0 )
        pointb.pos[angle+(360*loc)] = vector( 0, 0, 0 )

        if not use_lines : lines[angle+(360*loc)].pos[1]=(offset*c,0,offset*s)
        if not use_outer_line :
            outer_line.pos[angle+(360*loc)]=(offset*c,0,offset*s)
            outer_line.color[angle+(360*loc)] = (0.1, 0.1, 0.2)
        
        
        # display the sample
        if x1 & 0x80: # is the flag for "bad data" set?
            # yes it's bad data
            lines[angle+(360*loc)].pos[1]=(offset*c,0,offset*s)
            outer_line.pos[angle+(360*loc)]=(offset*c,0,offset*s)
            outer_line.color[angle+(360*loc)] = (0.1, 0.1, 0.2)
        else:
            # no, it's cool
            if not x1 & 0x40:
                # X+1:6 not set : quality is OK
                if use_intensity or use_height:
                    if use_height:
                        if dist_z <= -10:
                            point.color[angle+(360*loc)] = (1.,0.6,0.) # orange  
                        elif dist_z <= 200:
                            point.color[angle+(360*loc)] = (1.,1,0.) # yellow
                        elif dist_z <= 500:
                            point.color[angle+(360*loc)] = (0.,1,0.) # green 
                        else:
                            point.color[angle+(360*loc)] = (0.,0.,1.) # blue                          
                    if use_intensity:                      
                        if quality < 25:
                            point.color[angle+(360*loc)] = (1.,0.6,0.)
                            print "orange"
                        elif quality < 50:
                            point.color[angle+(360*loc)] = (1.,1.,0.)
                            print "yellow"
                        elif quality < 80:
                            point.color[angle+(360*loc)] = (0.,0.,1.)
                            print "blue"
                if use_points and dist_z > -10: 
                    point.pos[angle+(360*loc)] = vector( dist_x, dist_z, dist_y)
                    if storing == True:
                        lidar_df.loc[angle+(360*loc)] = [dist_x, dist_y, dist_z, quality, 0]                             
                if use_lines : lines[angle+(360*loc)].color[1] = (1,0,0)
                if use_outer_line : outer_line.color[angle+(360*loc)] = (1,0,0)
            else:
                # X+1:6 set : Warning, the quality is not as good as expected
                if use_points and dist_z > -10: 
                    pointb.pos[angle+(360*loc)] = vector( dist_x,dist_z, dist_y)
                    if storing == True:
                        lidar_df.loc[angle+(360*loc)] = [dist_x, dist_y, dist_z, quality, 1] 
                if use_lines : lines[angle+(360*loc)].color[1] = (0.4,0,0)
                if use_outer_line : outer_line.color[angle+(360*loc)] = (0.4,0,0)
            if use_lines : lines[angle+(360*loc)].pos[1]=( dist_x, dist_z, dist_y)
            if use_outer_line : outer_line.pos[angle+(360*loc)]=( dist_x, dist_z, dist_y)            
コード例 #24
0
letternames= os.listdir(path_original_letters)

for letter in letternames:
    letterpath = path_original_letters + '/' + letter
    newletterpath = path_new_letters + '/' + letter + '/'
    if not os.path.exists(newletterpath):
        os.mkdir(newletterpath)

            
    imagenames = os.listdir(letterpath)
    for imagename in imagenames[0:5]:
        imagepath = letterpath + '/' + imagename
        image = cv2.imread(imagepath,0)           #read as grayscale image
        #print(newletterpath)
        #Now we will do the follow with all images: 
        rotation(image, newletterpath + imagename[0:-4], [5,10,15,20,25,30])
        noise(image, newletterpath + imagename[0:-4], [1.2,1.4,1.6,1.8,2])
        translation(image, newletterpath + imagename[0:-4],[3,5])
        shearing(image, newletterpath + imagename[0:-4],[0,0.5,0.8,1.2])
        
        
        
        
        
        

        
        
        

        
コード例 #25
0
ファイル: cube.py プロジェクト: undu/pyray
def teserract_body_diagonal(width=15,
                            im_ind=70,
                            scale=500,
                            shift=np.array([1000, 1000, 0, 0, 0]),
                            basepath='.\\'):
    """
    @MoneyShot
        basepath in main repo: images\\RotatingCube\\
        Draws a four dimensional teserract with two tetrahedral
        and one octahedral planes visible.
    """
    c1 = Cube(4)
    r = np.eye(4)
    r[:3, :3] = rotation(3, np.pi * 2 * 27 / 80.0)
    r1 = rotation(4, np.pi * 2 * im_ind / 80.0)
    r = np.dot(r, r1)
    [im, draw] = c1.plot_edges(r)
    rotated_vertices = np.transpose(np.dot(r, np.transpose(
        c1.vertice_matrix))) * scale + shift[:4]
    hexag = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 2]
    ]]
    sqr1 = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 3]
    ]]
    try:
        draw.polygon(jarvis_convex_hull(sqr1), (255, 0, 0, 60))
    except:
        print("err")
    for ver in c1.vertices[c1.vertice_coordinate_sums == 3]:
        ver.plot(r, draw, (255, 0, 0), 10)
        for ver1 in c1.vertices[c1.vertice_coordinate_sums == 3]:
            e = Edge(ver, ver1)
            e.plot(r, draw, (255, 0, 0), width=2)
    try:
        draw.polygon(jarvis_convex_hull(hexag), (0, 255, 0, 30))
    except:
        print("err")
    for ver in c1.vertices[c1.vertice_coordinate_sums == 1]:
        ver.plot(r, draw, (0, 0, 255), 10)
        for ver1 in c1.vertices[c1.vertice_coordinate_sums == 1]:
            e = Edge(ver, ver1)
            e.plot(r, draw, (0, 0, 255))
    for ed in [(5, 3), (5, 6), (5, 9), (5, 12), (10, 3), (10, 6), (10, 9),
               (10, 12), (3, 6), (3, 9), (12, 6), (12, 9)]:
        v1 = rotated_vertices[ed[0]]
        v2 = rotated_vertices[ed[1]]
        draw.line((v1[0], v1[1], v2[0], v2[1]), fill=(0, 255, 0), width=4)
    for ver in c1.vertices[c1.vertice_coordinate_sums == 2]:
        ver.plot(r, draw, (0, 255, 0), 10)
    sqr2 = rotated_vertices[[
        i.index for i in c1.vertices[c1.vertice_coordinate_sums == 1]
    ]]
    try:
        draw.polygon(jarvis_convex_hull(sqr2), (0, 0, 255, 60))
    except:
        print("err")
    v1 = rotated_vertices[0]
    v2 = rotated_vertices[15]
    draw.line((v1[0], v1[1], v2[0], v2[1]), fill=(255, 255, 255), width=2)
    im.save(basepath + 'im' + str(im_ind) + '.png')
コード例 #26
0
def best_direction(j=19.5,
                   im_ind=0,
                   scale=250,
                   shift=np.array([1200, 580, 0]),
                   draw1=None):
    font = ImageFont.truetype("arial.ttf", 75)
    # For the axes.
    [a, b, c] = np.array([2.5, 2.5, -2.5]) * 410 / 200

    ## Rotation matrices.
    r = rotation(3, 2 * np.pi * j / 30.0)
    r1 = np.eye(4)
    r1[:3, :3] = r

    ## Image objects.
    if draw1 is None:
        im = Image.new("RGB", (2048, 2048), "black")
        draw = ImageDraw.Draw(im, 'RGBA')
    else:
        draw = draw1

    ## Create the axes.
    render_scene_4d_axis(draw, r1, 4, scale=scale, shift=shift)
    pt1 = np.dot(r, np.array([a, 0, 0])) * scale + shift[:3]
    pt2 = np.dot(r, np.array([0, b, 0])) * scale + shift[:3]
    pt3 = np.dot(r, np.array([0, 0, c])) * scale + shift[:3]

    ## The point where this plane extends.
    pt4 = np.dot(r, np.array([a, b, -c])) * scale + shift[:3]

    draw.line((pt1[0], pt1[1], pt2[0], pt2[1]), fill=(200, 80, 100), width=3)
    draw.line((pt1[0], pt1[1], pt2[0], pt2[1]), fill='orange', width=3)

    draw.polygon([(pt1[0], pt1[1]), (pt3[0], pt3[1]), (pt2[0], pt2[1])],
                 (200, 80, 100, 100))
    draw.polygon([(pt1[0], pt1[1]), (pt4[0], pt4[1]), (pt2[0], pt2[1])],
                 (200, 80, 100, 120))
    draw.line((shift[0], shift[1], pt3[0], pt3[1]), fill="yellow", width=7)
    draw.line((shift[0], shift[1], pt1[0], pt1[1]), fill="yellow", width=7)
    draw.line((shift[0], shift[1], pt2[0], pt2[1]), fill="yellow", width=7)

    ## Draw the x-y grid.
    drawXYGrid(draw, r, 1.25, scale=scale, shift=shift)

    ## We start at 45 degrees and trace a circular arc from there.
    pt_1 = np.array([a / 2.0, b / 2.0, 0])
    arxExt = int(180 * im_ind / 10.0)
    draw_circle_x_y(draw=draw,
                    r=r,
                    center=pt_1[:2],
                    radius=1,
                    start=np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0]),
                    arcExtent=arxExt,
                    scale=scale,
                    shift=shift)
    project_circle_on_plane(draw=draw,
                            r=r,
                            center=pt_1[:2],
                            radius=1,
                            plane=np.array([a, b, c]),
                            start=np.array([1 / np.sqrt(2), 1 / np.sqrt(2),
                                            0]),
                            arcExtent=arxExt,
                            scale=scale,
                            shift=shift)

    ## Draw a point right at the center of the orange line.
    pt = np.dot(r, pt_1) * scale + shift[:3]
    width = 10
    draw.ellipse((pt[0] - width, pt[1] - width, pt[0] + width, pt[1] + width),
                 fill=(102, 255, 51))

    # We start at 45 degrees and trace a circular arc from there.
    theta = np.arctan(a / b) + np.pi * im_ind / 10.0
    pt_2 = pt_1 + 1.0 * np.array([np.cos(theta), np.sin(theta), 0])
    arrowV1(draw, r, pt_1, pt_2, scale=scale, shift=shift)

    ## Draw a pink triangle with vertices: head of arrow, tail of arrow, projection on plane.
    arrow_w_projection(im, draw, r, pt_1, pt_2, plane=np.array([a, b, c]))

    ## If you didn't provide the draw object, we will save the image.
    if draw1 is None:
        im.save('.\\im' + str(im_ind) + '.png')