Пример #1
0
def rotate(img, angle):
    center = (img.width / 2.0, img.height / 2.0)
    rot_mat = cv.CreateMat(2, 3, cv.CV_32FC1)
    cv.GetRotationMatrix2D(center, angle, 1.0, rot_mat)
    dst = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 1)
    cv.WarpAffine(img, dst, rot_mat, fillval=255)
    return dst
Пример #2
0
def align_affine(imgA, imgB, ptsA, ptsB):
    """ Aligns IMGB to IMGA, given that the points in PTSA correspond
    to the points in PTSB. Returns both the aligned IMGB and the
    affine transformation matrix.    
    """
    # 1.) Assume that transformation is 'rigid' (translation, rotation,
    # scaling). Solve the equation:
    #   Mx = x'
    # where x is the coordinates in imgB: (x, y, 1)
    # x' is the coordinates in imgA: (x', y', 1)
    # and M is the affine transformation matrix, which is a 2x3
    # matrix consisting of the affine-trans. coefficients:
    #     M  =  | A B |  =  | a_00 a_01 b_0 |
    #                       | a_10 a_11 b_1 |
    # where A is the rotation+scaling matrix, B is the translation
    # matrix, and | A B | is the augmented matrix (that allows us to
    # apply an affine trans. to a point (x, y) with a single matrix
    # operation:    
    #     (x',y',1) = M * (x,y,1)
    
    mapMat = cv.CreateMat(2, 3, cv.CV_32F)
    # Note: Here, we use the three pairs of cooresponding points to
    # solve for the affine transformation matrix M.
    cv.GetAffineTransform(ptsB, ptsA, mapMat)
    
    # 2.) Now that we have the affine transformation matrix M, we
    # apply it to imgB to align it to imgA:
    outMat = cv.CreateMat(imgB.rows, imgB.cols, imgB.type)
    cv.WarpAffine(imgB, outMat, mapMat)
    
    return outMat, mapMat
Пример #3
0
def imtransform(I, H0, fillval=np.nan):
    # transform image using center as origin
    if len(I.shape) == 3:
        Iout = np.copy(I)
        Iout[:, :, 0] = imtransform(I[:, :, 0], H0, fillval=fillval)
        Iout[:, :, 1] = imtransform(I[:, :, 1], H0, fillval=fillval)
        Iout[:, :, 2] = imtransform(I[:, :, 2], H0, fillval=fillval)
        return Iout
    else:
        T0 = np.eye(3)
        T0[0, 2] = I.shape[1] / 2.0
        T0[1, 2] = I.shape[0] / 2.0
        T1 = np.eye(3)
        T1[0, 2] = -I.shape[1] / 2.0
        T1[1, 2] = -I.shape[0] / 2.0
        H = np.dot(np.dot(T0, H0), T1)

        # transform each channel separately
        if not I.flags.c_contiguous:
            I = np.copy(I)

        Icv = cv.fromarray(I)
        I1cv = cv.CreateMat(I.shape[0], I.shape[1], Icv.type)

        H = H[:2]
        H = cv.fromarray(H)
        # cv.WarpPerspective(Icv,I1cv,cv.fromarray(np.copy(H)),fillval=-1);
        cv.WarpAffine(Icv, I1cv, H)  # ,fillval=fillval);
        I1 = np.asarray(I1cv)
        # I1[np.nonzero(I1<0)]=fillval
        return I1
Пример #4
0
	def rotacion_y_posicion_robot(self,robo_x=200,robo_y=100,robo_th=80):
		"""
		\brief graficar el robot en el lienzo de mapa 
		\param self no se necesita incluirlo al utilizar la funcion ya que se lo pone solo por ser la definicion de una clase
		\param robo_x coordenada x de la odometria del robot 
		\param robo_y coordenada y de la odometria del robot 
		\param robo_th Valor Th del robot
		\return Nada
		"""
		image_mapa=cv.LoadImage(self.nombre_archivo1, cv.CV_LOAD_IMAGE_COLOR)
		dimensiones_robot=self.dimensiones_robot
		image1=cv.CreateImage(dimensiones_robot,8,3)
		image_mascara=cv.CreateImage(dimensiones_robot,8,1)
		
		##rotacion
		#Rotar el robot
		src_center=dimensiones_robot[0]/2,dimensiones_robot[1]/2
		rot_mat=cv.CreateMat( 2, 3, cv.CV_32FC1 )
		cv.GetRotationMatrix2D(src_center, robo_th, 1.0,rot_mat);
		cv.WarpAffine(self.robot,image1,rot_mat)
		#crear filtro para negro
		cv.InRangeS(image1,cv.RGB(0,0,0),cv.RGB(14,14,14),image_mascara)
		cv.Not(image_mascara,image_mascara)
		#cv.ReleaseImage(image1)
		
		#reducir y posicion
		cv.SetImageROI(image_mapa,(robo_x,robo_y, dimensiones_robot[0], dimensiones_robot[1]));
		cv.Copy(image1,image_mapa,mask=image_mascara)
		cv.ResetImageROI(image_mapa);
		cv.SaveImage(self.nombre_archivo, image_mapa) #Saves the image#
Пример #5
0
def rotate(im, angle):
    """
	Rotates image by angle degrees clockwise.
	
	**Parameters:**
		* im (cvArr) - The source image.
		* angle (float) - Angle in degrees.
	
	**Returns:**
		The rotated image.
	
	.. todo::
		* Arguments to specifcy background colour and clockwise/anti-clockwise.
		* Enclosed rectangle formula.
	"""
    centre = ((im.width - 1) / 2, (im.height - 1) / 2)
    rot = cv.CreateMat(2, 3, cv.CV_32FC1)
    cv.GetRotationMatrix2D(centre, -angle, 1.0, rot)
    dst = create(im)
    cv.WarpAffine(im, dst, rot)

    # Code in progress to return the new rectangle contained in the rotated image

    # w = float(im.width)
    # 	h = float(im.height)
    # 	angle = (angle/360.0)*2*math.pi
    # 	width = w/(math.sin(angle)*(h/w + (math.cos(angle)/math.sin(angle))))
    # 	height = (w/h)*width
    # pt1 = (centre[0]-int(width/2), centre[1]-int(height/2))
    # pt2 = (centre[0]+int(width/2)-1, centre[1]+int(height/2)-1)
    # cv.Rectangle(dst, pt1, pt2, 255)
    return dst
Пример #6
0
def rotateImage(image, angle):
    image_center = tuple(numpy.array(cv.GetSize(image))/2)
    rot_mat = cv.CreateMat(2, 3, cv.CV_32F)
    cv.GetRotationMatrix2D(image_center, angle, 1.0, rot_mat)
    result = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 
    cv.WarpAffine(image, result, rot_mat)

    return result
Пример #7
0
def rotate(src, center, angle):
    mapMatrix = cv.CreateMat(2,3,cv.CV_64F)
    #cv.GetRotationMatrix2D( center, 450 - angle, 1.0, mapMatrix)
    cv.GetRotationMatrix2D( center, 270 - angle, 1.0, mapMatrix)
    dst = cv.CreateImage( cv.GetSize(src), src.depth, src.nChannels)
    cv.SetZero(dst)
    cv.WarpAffine(src, dst, mapMatrix)
    return dst
Пример #8
0
def get_image(camera, width, height, writer=None, s=None, rotate=True):
    im = cv.QueryFrame(camera)
    imrot = cv.CloneImage(im)
    if rotate:
        cv.WarpAffine(im, imrot, gMapping)
    if writer is not None:
        write_send(camera, imrot, writer, s)
    # im = Image.fromstring("RGB", cv.GetSize(im), im.tostring(), "raw", "BGR")
    return imrot
Пример #9
0
    def rotate_image(self, image, angle, around=None):
        if around is None:
            around = (0, 0)
        rotate = cv.CreateImage(cv.GetSize(image), image.depth, 1)
        rotate = cv.CloneImage(image)

        mapping = cv.CreateMat(2, 3, cv.CV_32FC1)
        cv.GetRotationMatrix2D(around, angle, 1, mapping)
        cv.WarpAffine(image, rotate, mapping)

        return rotate
Пример #10
0
    def scaleRot(self, im_small, d_scale, d_heading):
        cv.GetRotationMatrix2D((self.P1[0, 2] / self.performance.small_factor,
                                self.P1[1, 2] / self.performance.small_factor),
                               -d_heading, d_scale, self.rotscale_map)
        #cv.GetRotationMatrix2D((self.size_small[1]/2, self.size_small[0]/2), -d_heading, d_scale, self.rotscale_map)
        #self.rotscale_map = cv.fromarray(cv2.getRotationMatrix2D((np.float32(self.size_small[1])/2,np.float32(self.size_small[0])/2), -d_heading, d_scale))

        #alpha = d_scale * np.cos(-d_heading * np.pi/180)
        #beta = d_scale * np.sin(-d_heading * np.pi/180)
        #self.rotscale_map[0,2] = (1-alpha)*680 - beta*512
        #self.rotscale_map[1,2] = beta*680 + (1-alpha)*512

        cv.WarpAffine(im_small, im_small, self.rotscale_map)
Пример #11
0
    def img(self):
        '''return a cv image for the icon'''
        SlipThumbnail.img(self)

        if self.rotation:
            # rotate the image
            mat = cv.CreateMat(2, 3, cv.CV_32FC1)
            cv.GetRotationMatrix2D((self.width / 2, self.height / 2),
                                   -self.rotation, 1.0, mat)
            self._rotated = cv.CloneImage(self._img)
            cv.WarpAffine(self._img, self._rotated, mat)
        else:
            self._rotated = self._img
        return self._rotated
Пример #12
0
def extract_plate(image, cluster):
	"""De-skew and extract a detected plate from an image."""
	cluster = list(cluster)
	cluster.sort(cmp=lambda x,y: cmp(x.cx,y.cx))
	o = cluster[-1].cy - cluster[0].cy
	h = cluster[0].dist_to(cluster[-1])
	angle = math.asin(o/h)
	matrix = cv.CreateMat(2, 3, cv.CV_32FC1)
	cx = (cluster[0].cx + cluster[-1].cx)/2.0
	cy = (cluster[0].cy + cluster[-1].cy)/2.0
	getattr(cv,'2DRotationMatrix')((cx,cy), angle*180.0/math.pi, 1, matrix)
	warp = cv.CreateImage(cv.GetSize(image), 
		cv.IPL_DEPTH_8U, 3)
	cv.WarpAffine(image, warp, matrix)
	ret = cv.CreateImage((h+cluster[0].dia*3.0, cluster[0].dia*1.5), cv.IPL_DEPTH_8U, 3)
	cv.GetRectSubPix(warp, ret, (cx,cy))
	print cv.GetSize(ret)
	return ret
Пример #13
0
class image_converter:
    def __init__(self):
        self.image_pub = rospy.Publisher("image_topic_2", Image)

        cv.NamedWindow("Image window", 1)
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("usb_cam/image_raw", Image,
                                          self.callback)

    def callback(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv(data, "bgr8")
        except CvBridgeError, e:
            print e

        (cols, rows) = cv.GetSize(cv_image)
        zcx = cols / 2
        zcy = rows / 2
        if cols > 60 and rows > 60:
            cv.Circle(cv_image, (zcx, zcy), 10, 255)

        zoom_value = 100
        M = cv.CreateMat(2, 3, cv.CV_32FC1)
        M[0, 0] = zoom_value / 100.
        M[0, 1] = 0
        M[0, 2] = -zcx * (zoom_value / 100. - 1)
        M[1, 0] = 0
        M[1, 1] = zoom_value / 100.
        M[1, 2] = -zcy * (zoom_value / 100. - 1)

        cvi2 = cv_image
        cv.WarpAffine(cv_image, cvi2, M)

        cv.ShowImage("Image window", cv_image)
        cv.WaitKey(3)

        try:
            self.image_pub.publish(self.bridge.cv_to_imgmsg(cv_image, "bgr8"))
        except CvBridgeError, e:
            print e
Пример #14
0
def doRotate(image,
             alpha,
             fillval=0,
             resize=True,
             interpolation=cv.CV_INTER_CUBIC):
    matrix = cv.CreateMat(2, 3, cv.CV_32FC1)
    w, h = cv.GetSize(image)
    center = ((w - 1) / 2.0, (h - 1) / 2.0)
    cv.GetRotationMatrix2D(center, alpha, 1.0, matrix)
    if resize:
        d = sqrt(w * w + h * h)
        d2 = d / 2.0
        matrix[0, 2] += d2 - center[0]
        matrix[1, 2] += d2 - center[1]
        d = int(d)
        size = (d, d)
    else:
        size = cv.GetSize(image)
    result = cv.CreateImage(size, image.depth, image.nChannels)
    cv.WarpAffine(image, result, matrix,
                  interpolation + cv.CV_WARP_FILL_OUTLIERS, fillval)
    return result
Пример #15
0
    def rotate(self, degrees):
        if (degrees > 180):
            # Flip around both axes
            cv.Flip(self.image, None, -1)
            degrees = degrees - 180

        img = self.image
        size = cv.GetSize(img)

        if (degrees / 90 % 2):
            new_size = (size[1], size[0])
            center = ((size[0] - 1) * 0.5, (size[0] - 1) * 0.5)
        else:
            new_size = size
            center = ((size[0] - 1) * 0.5, (size[1] - 1) * 0.5)

        mapMatrix = cv.CreateMat(2, 3, cv.CV_64F)
        cv.GetRotationMatrix2D(center, degrees, 1.0, mapMatrix)
        dst = cv.CreateImage(new_size, self.image_depth, self.image_channels)
        cv.SetZero(dst)
        cv.WarpAffine(img, dst, mapMatrix)
        self.image = dst
Пример #16
0
def doRotate(image,
             alpha,
             fillval=0,
             resize=True,
             interpolation=cv.CV_INTER_CUBIC):
    matrix = cv.CreateMat(2, 3, cv.CV_32FC1)
    w, h = cv.GetSize(image)
    center = ((w - 1) / 2.0, (h - 1) / 2.0)
    cv.GetRotationMatrix2D(center, alpha, 1.0, matrix)
    if resize:
        angle = rad(abs(alpha))
        nw = w * cos(angle) + h * sin(angle)
        nh = w * sin(angle) + h * cos(angle)
        ncenter = (nw / 2.0, nh / 2.0)
        matrix[0, 2] += ncenter[0] - center[0]
        matrix[1, 2] += ncenter[1] - center[1]
        size = (int(ceil(nw)), int(ceil(nh)))
    else:
        size = cv.GetSize(image)
    result = cv.CreateImage(size, image.depth, image.nChannels)
    cv.WarpAffine(image, result, matrix,
                  interpolation + cv.CV_WARP_FILL_OUTLIERS, fillval)
    return result
Пример #17
0
    if vars().has_key('centery'):
        zcy = centery
    else:
        zcy = rows / 2

    M = cv.CreateMat(2, 3, cv.CV_32FC1)
    M[0, 0] = zoom / 100.
    M[0, 1] = 0
    M[0, 2] = -zcx * (zoom / 100. - 1)
    M[1, 0] = 0
    M[1, 1] = zoom / 100.
    M[1, 2] = -zcy * (zoom / 100. - 1)

    cvi2 = cv_image
    cv.WarpAffine(cv_image, cvi2, M)

    return bridge.cv_to_imgmsg(cvi2, "bgr8")


# compare_images
#
# Compares two images (/sensor_msgs/Image) and estimates first norm
# of the difference between the pixel values by calculating the
# average difference for the set of each <step>'th pixel.
#
# Output
# 	Average pixel value difference
#
def compare_images(image1, image2, step=100):
    normdiff = 0.
Пример #18
0
# coding: utf-8

import cv, commands, sys, os

FOLDER_PATH = "/Users/satokazuki/Desktop/zikken5/G1_kirinuki/"
OUTPUT_PATH = "/Users/satokazuki/Desktop/zikken5/G1_database/"

img_list = os.listdir(FOLDER_PATH)
print img_list
count = 0

for img_name in img_list:
    angle = (0, 90, 180, 270)
    item = img_name.split(".")

    if item[1] == "png":
        im_in = cv.LoadImage(FOLDER_PATH + img_name)
        im_ro = cv.CreateImage(cv.GetSize(im_in), cv.IPL_DEPTH_8U, 3)
        rotate_mat = cv.CreateMat(2, 3, cv.CV_32FC1)
        count += 1

        for i in range(0, 4):
            cv.GetRotationMatrix2D((im_in.height / 2, im_in.width / 2),
                                   angle[i], 1, rotate_mat)
            cv.WarpAffine(im_in, im_ro, rotate_mat)
            cv.SaveImage(OUTPUT_PATH + item[0] + "_" + str(i) + ".png", im_ro)
            count += 1

print count
Пример #19
0
    r = 28 + j * 4
    mr = r * math.sqrt(2)
    y += mr * 1.8
    test += [(str(deg) + "abcdefgh"[j], (50 + deg * 11, y),
              math.pi * deg / 180, r) for deg in range(0, 90, 10)]

for (msg, (x, y), angle, r) in test:
    map = cv.CreateMat(2, 3, cv.CV_32FC1)
    corners = [(x + r * math.cos(angle + th), y + r * math.sin(angle + th))
               for th in [0, math.pi / 2, math.pi, 3 * math.pi / 4]]
    src = mkdmtx(msg)
    (sx, sy) = cv.GetSize(src)
    cv.GetAffineTransform([(0, 0), (sx, 0), (sx, sy)], corners[:3], map)
    temp = cv.CreateMat(bg.rows, bg.cols, cv.CV_8UC3)
    cv.Set(temp, cv.RGB(0, 0, 0))
    cv.WarpAffine(src, temp, map)
    cv.Or(temp, bg, bg)

cv.ShowImage("comp", bg)
scribble = cv.CloneMat(bg)

if 0:
    for i in range(10):
        df.find(bg)

for (sym, coords) in df.find(bg).items():
    print sym
    cv.PolyLine(scribble, [coords],
                1,
                cv.CV_RGB(255, 0, 0),
                1,
def apply_rot(I, H):
    Idst = cv.CreateImage(cv.GetSize(I), I.depth, I.channels)
    cv.WarpAffine(I, Idst, H, fillval=255.0)
    return Idst
Пример #21
0
def processInput():

    print inputArgs.sessionFolder

    scriptDir = os.path.dirname(os.path.abspath(__file__))

    os.system("touch /run/shm/attitude2video_opencv.lock")

    data_yaw = []
    data_pitch = []
    data_roll = []

    data_speed = []
    data_altitude = []
    data_climb = []

    sourceFile_yaw = open(
        inputArgs.sessionFolder[0] + "/logs/interpolated_yaw_30fps.txt", 'r')
    for line in sourceFile_yaw:
        data_yaw.append(float(line))
    sourceFile_yaw.close()

    sourceFile_pitch = open(
        inputArgs.sessionFolder[0] + "/logs/interpolated_pitch_30fps.txt", 'r')
    for line in sourceFile_pitch:
        data_pitch.append(float(line))
    sourceFile_pitch.close()

    sourceFile_roll = open(
        inputArgs.sessionFolder[0] + "/logs/interpolated_roll_30fps.txt", 'r')
    for line in sourceFile_roll:
        data_roll.append(float(line))
    sourceFile_roll.close()

    sourceFile_speed = open(
        inputArgs.sessionFolder[0] + "/logs/interpolated_speed_30fps.txt", 'r')
    for line in sourceFile_speed:
        data_speed.append(float(line) * 3600 / 1000)
    sourceFile_speed.close()

    sourceFile_altitude = open(
        inputArgs.sessionFolder[0] + "/logs/interpolated_altitude_30fps.txt",
        'r')
    for line in sourceFile_altitude:
        data_altitude.append(float(line))
    sourceFile_altitude.close()

    sourceFile_climb = open(
        inputArgs.sessionFolder[0] +
        "/logs/interpolated_altitude_speed_30fps.txt", 'r')
    for line in sourceFile_climb:
        data_climb.append(float(line))
    sourceFile_climb.close()

    # create working directory in shared memmory
    if not os.path.exists("/dev/shm/attitude2video_opencv"):
        os.makedirs("/dev/shm/attitude2video_opencv")

        # prepare image templates
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/speed.png /dev/shm/attitude2video_opencv/speed.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/climb.png /dev/shm/attitude2video_opencv/climb.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/center.png /dev/shm/attitude2video_opencv/center.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/horizon.png /dev/shm/attitude2video_opencv/horizon.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/terrain.png /dev/shm/attitude2video_opencv/terrain.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/compass.png /dev/shm/attitude2video_opencv/compass.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/altitude.png /dev/shm/attitude2video_opencv/altitude.png"
        )
        os.system(
            "cp " + scriptDir +
            "/resources_opencv/background.png /dev/shm/attitude2video_opencv/background.png"
        )

    # create working directory
    if not os.path.exists(inputArgs.sessionFolder[0] + "/media/work"):
        os.makedirs(inputArgs.sessionFolder[0] + "/media/work")
    if not os.path.exists(inputArgs.sessionFolder[0] +
                          "/media/work/attitude_opencv"):
        os.makedirs(inputArgs.sessionFolder[0] + "/media/work/attitude_opencv")

    ## Apptly named MAGIC
    # But before that, let's load the templates
    originalSpeed = cv.LoadImage("/dev/shm/attitude2video_opencv/speed.png")
    originalClimb = cv.LoadImage("/dev/shm/attitude2video_opencv/climb.png")
    originalCenter = cv.LoadImage("/dev/shm/attitude2video_opencv/center.png")
    originalHorizon = cv.LoadImage("/dev/shm/attitude2video_opencv/horizon.png"
                                   )  # -1 to load with alpha channel
    originalTerrain = cv.LoadImage(
        "/dev/shm/attitude2video_opencv/terrain.png")
    originalCompass = cv.LoadImage(
        "/dev/shm/attitude2video_opencv/compass.png")
    originalAltitude = cv.LoadImage(
        "/dev/shm/attitude2video_opencv/altitude.png")

    for x in range(0, len(data_speed)):
        progressbar(((x * 1.0 + 1) / len(data_speed)), "Rendering openCV:",
                    "(" + str(x + 1) + "/" + str(len(data_speed)) + ") " +
                    "attitude_%07d.jpg" % (x + 1), 20)
        #for x in range(0,1):
        currentSpeed = cv.CloneImage(originalSpeed)
        currentClimb = cv.CloneImage(originalClimb)
        currentCenter = cv.CloneImage(originalCenter)
        currentHorizon = cv.CloneImage(originalHorizon)
        currentTerrain = cv.CloneImage(originalTerrain)
        currentCompass = cv.CloneImage(originalCompass)
        currentAltitude = cv.CloneImage(originalAltitude)

        # 0 ------------------------------------------------

        # Rotate center
        picCenter = (originalHorizon.width / 2.0, originalHorizon.height / 2.0)
        outputMatrix = cv.CreateMat(2, 3, cv.CV_32F)
        cv.GetRotationMatrix2D(
            picCenter, (data_roll[x]), 1.0, outputMatrix
        )  # Positive number goes counter-clockwise, counter to what the original code did. Ergo, do * away with -1
        cv.WarpAffine(originalHorizon,
                      currentHorizon,
                      outputMatrix,
                      cv.CV_WARP_FILL_OUTLIERS + cv.CV_INTER_LINEAR,
                      fillval=(0, 0, 0, 0))

        # Rotate horizon
        picCenter = (originalCenter.width / 2.0, originalCenter.height / 2.0)
        outputMatrix = cv.CreateMat(2, 3, cv.CV_32F)
        cv.GetRotationMatrix2D(picCenter, (data_roll[x]), 1.0, outputMatrix)
        cv.WarpAffine(originalCenter,
                      currentCenter,
                      outputMatrix,
                      cv.CV_WARP_FILL_OUTLIERS + cv.CV_INTER_LINEAR,
                      fillval=(0, 0, 0, 0))

        # 1 ------------------------------------------------

        odmik = data_pitch[x] * 3.0 * -1.0  # Reverse it again.
        width = 640
        height = 360
        picCenter = (currentHorizon.width / 2.0, currentHorizon.height / 2.0)
        regionOfInterest = (int(picCenter[0] - (width / 2.0)),
                            int(picCenter[1] - (height / 2.0) + (odmik)),
                            int(width), int(height))
        thirdHorizon = cv.GetSubRect(currentHorizon, regionOfInterest)

        # Instead of copy-ing we do subtraction. Works, since we're using (mostly) black for displaying things. Templates need to be alpha-less and inverted.
        cv.Sub(thirdHorizon, originalTerrain, thirdHorizon)
        cv.Sub(thirdHorizon, currentCenter, thirdHorizon)

        # 2 ------------------------------------------------
        zacetnaPozicija = width / 2.0
        if data_yaw[x] <= 180:
            zacetnaPozicija = zacetnaPozicija + 3.9 * data_yaw[x]
        else:
            zacetnaPozicija = zacetnaPozicija + 3.9 * (360 - data_yaw[x])

        # Speed imporvement. Which isn't faster. Yay.
        compassHeight = 50
        regionOfInterest = (int(currentCompass.width / 2.0 - zacetnaPozicija),
                            int(0), int(width), int(compassHeight))
        currentCompass = cv.GetSubRect(currentCompass, regionOfInterest)
        regionOfInterest = (int(0), int(0), int(width), int(compassHeight))
        pointerToSpace = cv.GetSubRect(thirdHorizon, regionOfInterest)
        cv.Sub(pointerToSpace, currentCompass, pointerToSpace)

        # 3 ------------------------------------------------

        speedCenter = (originalSpeed.width / 2.0, originalSpeed.height / 2.0)
        speedWidth = originalSpeed.width
        speedHeight = originalSpeed.height
        zacetnaPozicija = speedHeight / 2.0
        if data_speed[x] < 0:
            zacetnaPozicija = zacetnaPozicija - 210
        elif data_speed[x] >= 100:
            zacetnaPozicija = zacetnaPozicija + 210
        else:
            zacetnaPozicija = zacetnaPozicija + (200 - (data_speed[x] * 4))

        doDol = speedHeight - zacetnaPozicija
        if (doDol > 130):
            doDol = 130

        doGor = zacetnaPozicija
        if (doGor > 130):
            doGor = 130

        regionOfInterest = (int(0), int(zacetnaPozicija - doGor),
                            int(speedWidth), int(doDol + doGor))
        currentSpeed = cv.GetSubRect(originalSpeed, regionOfInterest)

        regionOfInterest = (int(width / 2.0 - 190 - currentSpeed.width / 2.0),
                            int(height / 2.0 - doGor), int(speedWidth),
                            int(doGor + doDol))

        pointerToWhereToCopySpeed = cv.GetSubRect(thirdHorizon,
                                                  regionOfInterest)
        cv.Sub(pointerToWhereToCopySpeed, currentSpeed,
               pointerToWhereToCopySpeed)

        # 4 ------------------------------------------------

        lokalniOdmik = 0
        if data_altitude[x] < 0:
            lokalniOdmik = 2010
        elif data_altitude[x] >= 1000:
            lokalniOdmik = -2010
        else:
            lokalniOdmik = -(2000 - (data_altitude[x] * 4))

        temp = currentAltitude.height / 2.0

        doDol = (temp + lokalniOdmik)
        if (doDol > 130):
            doDol = 130

        doGor = temp - lokalniOdmik
        if (doGor > 130):
            doGor = 130

        regionOfInterest = (int(0),
                            int(currentAltitude.height / 2.0 - lokalniOdmik -
                                doGor), int(speedWidth), int(doGor + doDol))

        cutAltitude = cv.GetSubRect(currentAltitude, regionOfInterest)

        regionOfInterest = (int(width / 2.0 + 160), int(height / 2.0 - doGor),
                            int(70), int(doGor + doDol))
        pointerToWhereToCopyAltitude = cv.GetSubRect(thirdHorizon,
                                                     regionOfInterest)

        cv.Sub(pointerToWhereToCopyAltitude, cutAltitude,
               pointerToWhereToCopyAltitude)

        #   ------------------------------------------------
        lokalniOdmik = 0
        if data_climb[x] < -10:
            lokalniOdmik = -410
        elif data_climb[x] >= 10:
            lokalniOdmik = 410
        else:
            lokalniOdmik = ((data_climb[x] * 4 * 10))

        temp = currentClimb.height / 2.0

        doDol = (temp + lokalniOdmik)
        if (doDol > 130):
            doDol = 130

        doGor = temp - lokalniOdmik
        if (doGor > 130):
            doGor = 130

        regionOfInterest = (int(0),
                            int(currentClimb.height / 2.0 - lokalniOdmik -
                                doGor), int(speedWidth), int(doGor + doDol))

        cutClimb = cv.GetSubRect(currentClimb, regionOfInterest)

        regionOfInterest = (int(width / 2.0 + 245), int(height / 2.0 - doGor),
                            int(70), int(doGor + doDol))
        pointerToWhereToCopyClimb = cv.GetSubRect(thirdHorizon,
                                                  regionOfInterest)

        cv.Sub(pointerToWhereToCopyClimb, cutClimb, pointerToWhereToCopyClimb)

        # 5 ------------------------------------------------

        cv.SaveImage("/dev/shm/attitude2video_opencv/composed.png",
                     thirdHorizon)
        os.system("cp /dev/shm/attitude2video_opencv/composed.png " +
                  inputArgs.sessionFolder[0] +
                  "/media/work/attitude_opencv/attitude_" + "%07d.png" %
                  (x + 1, ))


# CLEAR ALL VARIABLES! You know, memory leaks and such.
# 6 ------------------------------------------------

# KONEC
    os.system("avconv -r 30 -i " + inputArgs.sessionFolder[0] +
              "/media/work/attitude_opencv/attitude_" +
              "%07d.png -qscale 1 -b 1300k -vcodec libx264 " +
              inputArgs.sessionFolder[0] + "/media/attitude.mp4")

    # remove working directory with temporary files
    fileList = os.listdir(inputArgs.sessionFolder[0] +
                          "/media/work/attitude_opencv")
    for fileName in fileList:
        os.remove(inputArgs.sessionFolder[0] + "/media/work/attitude_opencv" +
                  "/" + fileName)
    os.rmdir(inputArgs.sessionFolder[0] + "/media/work/attitude_opencv")
    #os.rmdir(inputArgs.sessionFolder[0]+"/media/work")

    # remove working directory with temporary files in shared memmory
    fileList = os.listdir("/dev/shm/attitude2video_opencv")
    for fileName in fileList:
        os.remove("/dev/shm/attitude2video_opencv" + "/" + fileName)
    os.rmdir("/dev/shm/attitude2video_opencv")

    os.system("rm -f /run/shm/attitude2video_opencv.lock")
Пример #22
0
puntos_horizontales  = puntosParaTemplate (marcado, itemH)

print "horizontales: " + str (puntos_horizontales .__len__())

x1 = puntos_horizontales[0][0]
y1 = marcado.height-puntos_horizontales[0][1]

x2 = puntos_horizontales[1][0]
y2 = marcado.height-puntos_horizontales[1][1]

rot_mat = cv.CreateMat(2, 3, cv.CV_32F)
ang_rad = math.atan((y2-y1)/(x2-x1))
degrees = - (180 * ang_rad / math.pi)
cv.GetRotationMatrix2D( (marcado.width/2,marcado.height/2), degrees, 1, rot_mat );
cv.WarpAffine( marcado, marcadog, rot_mat );
opencv.cvReleaseImage(marcado)


puntos_horizontales  = puntosParaTemplate (marcado, itemH)
pos_respuesta  = puntosParaTemplate (marcadog, itemP)




print "respuestas: " + str (pos_respuesta.__len__())
#print "horizontal: " + str (pos_horizontal.__len__())
#print "sin marcar: " + str (sin_marcar.__len__())


for i in pos_respuesta:
Пример #23
0
def rotateImage(image, angle, center):
    rot_mat = cv.CreateMat(2, 3, cv.CV_32FC1)
    cv.GetRotationMatrix2D(center, angle * 180 / 3.14159, 1.0, rot_mat)
    result = cv.CloneImage(image)
    cv.WarpAffine(image, result, rot_mat)
    return result
Пример #24
0
framecounter = 0
w = 5
cv.NamedWindow("camera", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)

img = cv.QueryFrame(capture)
(r, c) = cv.GetSize(img)

imgGray = cv.CreateImage((r, c), cv.IPL_DEPTH_8U, 1)
imgRotate = cv.CreateImage((r, c), cv.IPL_DEPTH_8U, 1)
imgAvg = cv.CreateImage((r, c), cv.IPL_DEPTH_8U, 1)
rotMat = cv.CreateMat(2, 3, cv.CV_32FC1)

while True:
    img = cv.QueryFrame(capture)
    framecounter = framecounter + 1

    cv.CvtColor(img, imgGray, cv.CV_RGB2GRAY)

    cv.GetRotationMatrix2D((r / 2, c / 2), w * framecounter, 1.0, rotMat)
    cv.WarpAffine(imgGray, imgRotate, rotMat)

    alpha = 0.1
    cv.AddWeighted(imgAvg, 1.0 - alpha, imgRotate, alpha, 0.0, imgAvg)

    cv.ShowImage("camera", imgAvg)

    if cv.WaitKey(10) == 27:
        break
Пример #25
0
        imageRotatedWidth = minMaxCorners[0] - minMaxCorners[1] + 1
        imageRotatedHeight = minMaxCorners[2] - minMaxCorners[3] + 1

        #adjust the shift of the rotation
        rotMat[0, 2] -= minMaxCorners[1]
        rotMat[1, 2] -= minMaxCorners[3]

        #create new image to save the rotated image (rows = height, cols = width)
        imageRotated = cv.CreateMat(imageRotatedHeight, imageRotatedWidth,
                                    image.type)

        #perform the rotation:
        cv.WarpAffine(image,
                      imageRotated,
                      rotMat,
                      flags=interpolation_FLAG + cv.CV_WARP_FILL_OUTLIERS,
                      fillval=(255, 255, 255))

        #compute the new warped bounding box
        bb = [100000, 100000, 0, 0]
        for part in partsDict[imageNumber]:
            if part in partsToUse:
                currentPointX = partsDict[imageNumber][part][0]
                currentPointY = partsDict[imageNumber][part][1]
                warpedPointX = currentPointX * rotMat[
                    0, 0] + currentPointY * rotMat[0, 1] + rotMat[0, 2]
                warpedPointY = currentPointX * rotMat[
                    1, 0] + currentPointY * rotMat[1, 1] + rotMat[1, 2]

                finalPartLocsList.write(