Beispiel #1
0
def getData():

  for i in range (0 , classes):
    for j in range (0, train_samples):
      if j < 10 :
        fichero = "OCR/"+str(i) + "/"+str(i)+"0"+str(j)+".pbm"
      else:
        fichero = "OCR/"+str(i) + "/"+str(i)+str(j)+".pbm"
      src_image = cv.LoadImage(fichero,0)
      prs_image = preprocessing(src_image, size, size)
  
         
      
      row = cv.GetRow(trainClasses, i*train_samples + j)
      cv.Set(row, cv.RealScalar(i))
      row = cv.GetRow(trainData,   i*train_samples + j)

      img = cv.CreateImage( ( size, size ), cv.IPL_DEPTH_32F, 1) 
      

      cv.ConvertScale(prs_image,img,0.0039215, 0)


      data = cv.GetSubRect(img,  (0,0, size,size))
      row1 = cv.Reshape( data, 0, 1 )
     
      cv.Copy(row1, row)
Beispiel #2
0
def main():
    os.chdir(os.path.join(sys.argv[1], "motion"))
    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except OSError:
        pass

    #os.system("del klein\\*.png")
    os.system("convert motion_*.png -adaptive-resize 500x500! " +
              OUTPUT_DIR_NAME + "\\motion_%02d.png")

    os.chdir(OUTPUT_DIR_NAME)
    os.system("convert motion_*.png -append result.png")

    img = cv.LoadImageM("result.png")
    values = []

    for y in range(img.rows):
        value = cv.Get1D(cv.GetRow(img, y), 0)[0]
        values.append(value)

    values.sort(reverse=True)

    output_img = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
    for y in range(img.rows):
        for x in range(img.cols):
            cv.Set2D(output_img, y, x, cv.RGB(values[y], values[y], values[y]))

    cv.SaveImage("result_sorted.png", output_img)

    raw_input("- done -")
    return
Beispiel #3
0
def findY(imgSrc):
  mini = 0
  maxi = 0
  minFound = 0
  maxVal=cv.RealScalar(imgSrc.width * 255)
  for i in range(0,imgSrc.height):
    data = cv.GetRow(imgSrc, i);
    val  = cv.Sum(data);
    if(val[0] < maxVal[0]):
      maxi = i
      if(not minFound):
        mini = i
	minFound= 1
  return mini,maxi
Beispiel #4
0
def getpositions(im):
    leftmost = 0
    rightmost = 0
    topmost = 0
    bottommost = 0
    temp = 0
    for i in range(im.width):
        col = cv.GetCol(im, i)
        if cv.Sum(col)[0] != 0.0:
            rightmost = i
            if temp == 0:
                leftmost = i
                temp = 1
    for i in range(im.height):
        row = cv.GetRow(im, i)
        if cv.Sum(row)[0] != 0.0:
            bottommost = i
            if temp == 1:
                topmost = i
                temp = 2
    return (leftmost, rightmost, topmost, bottommost)
Beispiel #5
0
def getpositions(im):
    ''' this function returns leftmost,rightmost,topmost and bottommost values of the white blob in the thresholded image'''
    leftmost = 0
    rightmost = 0
    topmost = 0
    bottommost = 0
    temp = 0
    for i in range(im.width):
        col = cv.GetCol(im, i)
        if cv.Sum(col)[0] != 0.0:
            rightmost = i
            if temp == 0:
                leftmost = i
                temp = 1
    for i in range(im.height):
        row = cv.GetRow(im, i)
        if cv.Sum(row)[0] != 0.0:
            bottommost = i
            if temp == 1:
                topmost = i
                temp = 2
    return (leftmost, rightmost, topmost, bottommost)
Beispiel #6
0
def points_max_cols(img, color='green', threshold=240):
    """
    Read maximum pixel value in one color channel for each row
    """
    w, h = cv.GetSize(img)
    xy = list()

    gray = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)

    if color == 'red':
        cv.Split(img, None, None, gray, None)
    else:
        cv.Split(img, None, gray, None, None)

    for i in range(0, h):
        row = cv.GetRow(gray, i)
        minv, maxv, minl, maxl = cv.MinMaxLoc(row)

        if maxv > threshold:
            xy.append((maxl[0], i))

    return xy
Beispiel #7
0
    def show(self):
        """ Process and show the current frame """
        source = cv.LoadImage(self.files[self.index])
        width, height = cv.GetSize(source)

        center = (width / 2) + self.offset

        cv.Line(source, (center, 0), (center, height), (0, 255, 0), 1)

        if self.roi:
            x, y, a, b = self.roi

            print self.roi

            width, height = ((a - x), (b - y))
            mask = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)

            cv.SetImageROI(source, (x, y, width, height))
            cv.Split(source, None, None, mask, None)

            gray = cv.CloneImage(mask)

            cv.InRangeS(mask, self.thresholdMin, self.thresholdMax, mask)
            cv.And(mask, gray, gray)

            line = []
            points = []

            for i in range(0, height - 1):
                row = cv.GetRow(gray, i)

                minVal, minLoc, maxLoc, maxVal = cv.MinMaxLoc(row)

                y = i
                x = maxVal[0]
                point = (0, 0, height - i)

                if x > 0:
                    line.append((x, y))

                    s = x / sin(radians(self.camAngle))
                    x = s * cos(self.angles[self.index])
                    z = height - y
                    y = s * sin(self.angles[self.index])

                    point = (round(x, 2), round(y, 2), z)

                points.append(point)

            cv.PolyLine(source, [line], False, (255, 0, 0), 2, 8)
            cv.ResetImageROI(source)
            x, y, a, b = self.roi
            cv.Rectangle(source, (int(x), int(y)), (int(a), int(b)),
                         (255.0, 255, 255, 0))

        if self.roi:
            x, y, a, b = self.roi

            width, height = ((a - x), (b - y))
            mask = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)

            cv.SetImageROI(
                source, (x - width, y, width, height))  # moves roi to the left
            cv.Split(source, None, None, mask, None)

            gray = cv.CloneImage(mask)

            cv.InRangeS(mask, self.thresholdMin, self.thresholdMax, mask)
            cv.And(mask, gray, gray)

            line = []
            points2 = []

            for i in range(0, height - 1):
                row = cv.GetRow(gray, i)

                minVal, minLoc, maxLoc, maxVal = cv.MinMaxLoc(row)

                y = i
                x = maxVal[0]
                point = (0, 0, height - i)

                if x > 0:
                    line.append((x, y))

                    x = width - x
                    # left to the x-axis

                    s = x / sin(radians(self.camAngle))

                    x = s * cos(self.angles[self.index])
                    z = height - y  # 500 higher then the other.
                    y = s * sin(self.angles[self.index])

                    a = radians(300)

                    nx = (cos(a) * x) - (sin(a) * y)
                    ny = (sin(a) * x) + (cos(a) * y)

                    point = (nx, ny, z)

                points2.append(point)

            cv.PolyLine(source, [line], False, (255, 0, 0), 2, 8)
            cv.ResetImageROI(source)
            x, y, a, b = self.roi
            cv.Rectangle(source, (int(x), int(y)), (int(a), int(b)),
                         (255.0, 255, 255, 0))

        if self.mode == 'mask':
            cv.ShowImage('preview', mask)
            return

        if self.mode == 'record' and self.roi:
            font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 1)
            cv.PutText(source, "recording %d" % self.index, (20, 20), font,
                       (0, 0, 255))
            self.points.extend(points)
            self.points2.extend(points2)
            #self.colors.extend(colors);

        cv.ShowImage('preview', source)
Beispiel #8
0
def main():
    os.chdir(sys.argv[1])

    #print "DELETE ALL FILES FIRST!"

    #tree = et.parse("project.xml")
    #movie = tree.getroot()
    #start_frame = int( movie.attrib["start_frame"] )
    #end_frame = int( movie.attrib["end_frame"] )

    f_shots = open("shots.txt")
    shots = [
        (int(start), int(end))
        for start, end in [line.split("\t")[0:2] for line in f_shots if line]
    ]
    f_shots.close()

    f_chapters = open("chapters.txt")
    chapters = [int(line) for line in f_chapters if line]
    f_chapters.close()
    '''# fix first and add last frame
	chapters[0] = start_frame
	chapters.append(end_frame)'''

    os.chdir("shot_colors")
    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except:
        pass

    filenames = glob.glob("shot_colors_*.png")

    last_shot_nr = 0
    ch = 1
    for i, shot in enumerate(shots):
        start_frame, end_frame = shot
        if ch == len(chapters):  # will this ever happen, freder?
            print("den rest noch")
            #print " ".join(filenames[last_shot_nr:])
            os.system("convert %s -append chapters/chapter_%02d.png" %
                      (" ".join(filenames[last_shot_nr:]), ch))
            break
        elif end_frame >= chapters[ch]:
            #if end_frame >= chapters[ch]:
            print("{} : {} -> {}".format(ch, last_shot_nr, i - 1))
            print(" ".join(filenames[last_shot_nr:i]))
            os.system("convert %s -append chapters/chapter_%02d.png" %
                      (" ".join(filenames[last_shot_nr:i]), ch))
            last_shot_nr = i
            ch += 1

    os.chdir(OUTPUT_DIR_NAME)

    for file_nr, file in enumerate(os.listdir(os.getcwd())):
        if os.path.isdir(file):
            continue

        img_orig = cv.LoadImageM(file)
        w, h = img_orig.cols, img_orig.rows

        img_hls = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 3)
        cv.CvtColor(img_orig, img_hls, cv.CV_BGR2HLS)

        output_img = cv.CreateImage((PIXELS_PER_COLOR * NUM_CLUSTERS, h),
                                    cv.IPL_DEPTH_8U, 3)

        # convert to numpy array
        a = numpy.asarray(cv.GetMat(img_hls))
        a = a.reshape(a.shape[0] * a.shape[1],
                      a.shape[2])  # make it 1-dimensional

        # set initial centroids
        init_cluster = []
        step = w / NUM_CLUSTERS
        #for x, y in [(0*step, h*0.1), (1*step, h*0.3), (2*step, h*0.5), (3*step, h*0.7), (4*step, h*0.9)]:
        for x, y in [(0 * step, h * 0.1), (1 * step, h * 0.1),
                     (2 * step, h * 0.3), (3 * step, h * 0.3),
                     (4 * step, h * 0.5), (5 * step, h * 0.5),
                     (6 * step, h * 0.7), (7 * step, h * 0.7),
                     (8 * step, h * 0.9), (9 * step, h * 0.9)]:
            x = int(x)
            y = int(y)
            init_cluster.append(a[y * w + x])

        centroids, labels = scipy.cluster.vq.kmeans2(a,
                                                     numpy.array(init_cluster))

        vecs, dist = scipy.cluster.vq.vq(a, centroids)  # assign codes
        counts, bins = scipy.histogram(vecs,
                                       len(centroids))  # count occurrences
        centroid_count = []
        for i, count in enumerate(counts):
            if count > 0:
                centroid_count.append((centroids[i].tolist(), count))

        centroid_count.sort(hls_sort2)

        px_count = w * h
        x = 0
        for item in centroid_count:
            count = item[1] * (PIXELS_PER_COLOR * NUM_CLUSTERS)
            count = int(math.ceil(count / float(px_count)))
            centroid = item[0]
            for l in range(count):
                if x + l >= PIXELS_PER_COLOR * NUM_CLUSTERS:
                    break
                for y in range(h):
                    cv.Set2D(output_img, y, x + l,
                             (centroid[0], centroid[1], centroid[2]))
            x += count

        output_img_rgb = cv.CreateImage(cv.GetSize(output_img),
                                        cv.IPL_DEPTH_8U, 3)
        cv.CvtColor(output_img, output_img_rgb, cv.CV_HLS2BGR)
        cv.SaveImage(file, output_img_rgb)

        # save to text-file
        if file_nr == 0:
            f_out = open(os.path.join("..", "..", "chapter_colors.txt"), "w")
            f_out.write("")  # reset
            f_out.close()

        f_out = open(os.path.join("..", "..", "chapter_colors.txt"), "a")
        row = cv.GetRow(output_img_rgb, 0)
        WIDTH = row.cols
        #print WIDTH

        data_items = []
        counter = 0
        last_px = cv.Get1D(row, 0)
        for i in range(WIDTH):
            px = cv.Get1D(row, i)
            if px == last_px:
                counter += 1
                if i == WIDTH - 1:
                    #f_out.write("%d, %d, %d, %d _ " % (int(last_px[2]), int(last_px[1]), int(last_px[0]), counter))
                    data_items.append(
                        "%d, %d, %d, %d" % (int(last_px[2]), int(
                            last_px[1]), int(last_px[0]), counter))
                continue
            else:
                #f_out.write("%d, %d, %d, %d _ " % (int(last_px[2]), int(last_px[1]), int(last_px[0]), counter))
                data_items.append("%d, %d, %d, %d" % (int(
                    last_px[2]), int(last_px[1]), int(last_px[0]), counter))
                counter = 1
                last_px = px

        print("{} colors missing".format(NUM_CLUSTERS - len(data_items)))
        for j in range(NUM_CLUSTERS -
                       len(data_items)):  # sometimes there are fewer colors
            data_items.append("0, 0, 0, 0")
        f_out.write(" _ ".join(data_items))
        f_out.write("\n")
        f_out.close()

    os.system("convert chapter_*.png -append _CHAPTERS.png")
    return
def main():
	project_root_dir = sys.argv[1]
	os.chdir(project_root_dir)
	os.chdir(os.path.join(OUTPUT_DIR_NAME, OUTPUT_DIR_NAME))
	
	output_img = cv.CreateImage((WIDTH, WIDTH), cv.IPL_DEPTH_8U, 3)
	
	print os.system("identify -format \"%k\" result.png")
	print "reducing colors to 10"
	os.system("convert result.png +dither -colors 10 result_quant.png")
	
	img_orig = cv.LoadImageM("result_quant.png")
	output_img = cv.CreateImage((WIDTH, WIDTH), cv.IPL_DEPTH_8U, 3)
	
	img_hls = cv.CreateImage(cv.GetSize(img_orig), cv.IPL_DEPTH_8U, 3)
	cv.CvtColor(img_orig, img_hls, cv.CV_BGR2HLS)
	
	pixels = numpy.asarray(cv.GetMat(img_hls))
	d = {}
	
	print "counting..."
	for line in pixels:
		for px in line:
			if tuple(px) in d:
				d[tuple(px)] += 1
			else:
				d[tuple(px)] = 1
	
	colors = d.keys()
	#print "%d pixels, %d colors" % (img_orig.width*img_orig.height, len(colors))
	
	print "sorting..."
	#colors.sort(hls_sort)
	colors = sort_by_distance(colors)
	
	px_count = img_orig.width * img_orig.height
	x_pos = 0
	
	print "building image..."
	for color in colors:
		l = d[color] / float(px_count)
		l = int(math.ceil( l*WIDTH ))
		
		for x in range(l):
			if x_pos+x >= WIDTH:
					break
			for y in range(WIDTH):
				cv.Set2D(output_img, y, x_pos+x, (int(color[0]), int(color[1]), int(color[2])))
		x_pos += l
	
	print "saving..."
	output_img_rgb = cv.CreateImage(cv.GetSize(output_img), cv.IPL_DEPTH_8U, 3)
	cv.CvtColor(output_img, output_img_rgb, cv.CV_HLS2BGR)
	cv.SaveImage("_RESULT.png", output_img_rgb)
	
	os.chdir( r"..\.." )
	f = open("colors.txt", "w")
	row = cv.GetRow(output_img_rgb, 0)
	
	counter = 0
	last_px = cv.Get1D(row, 0)
	for i in range(WIDTH):
		px = cv.Get1D(row, i)
		if px == last_px:
			counter += 1
			if i == WIDTH-1:
				f.write("%d, %d, %d, %d\n" % (int(last_px[2]), int(last_px[1]), int(last_px[0]), counter))
			continue
		else:
			f.write("%d, %d, %d, %d\n" % (int(last_px[2]), int(last_px[1]), int(last_px[0]), counter))
			counter = 1
			last_px = px
	f.close()
	
	return
class video_processor:
    def __init__(self):
        self.sub = rospy.Subscriber('usb_cam/image_raw', Image, self.callback)
        self.pub = rospy.Publisher('heading', Twist)
        self.speed = float(1)
        self.bridge = CvBridge()
        cv.NamedWindow("Input Video")
        #cv.NamedWindow("Blur Video")
        #cv.NamedWindow("HSV Video")
        #cv.NamedWindow("Hue Video")
        #cv.NamedWindow("Saturation Video")
        #cv.NamedWindow("Value Video")
        cv.NamedWindow("Red-Orange Video")
        cv.NamedWindow("White Video")
        cv.NamedWindow("Red-Orange and White Video")
        #cv.WaitKey(0)

    def callback(self, image_in):
        try:
            input_image = self.bridge.imgmsg_to_cv(image_in,"bgr8")
        except CvBridgeError, e:
            print e
        cv.ShowImage("Input Video", input_image)

        blur_image = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC3)
        cv.Smooth(input_image,blur_image,cv.CV_BLUR, 10, 10)
        #cv.ShowImage("Blur Video", proc_image)
        proc_image = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC3)
        cv.CvtColor(blur_image, proc_image, cv.CV_BGR2HSV)
        #cv.ShowImage("HSV Video", proc_image)
        split_image = [cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1),cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1),cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)]
        cv.Split(proc_image, split_image[0],split_image[1],split_image[2], None )
        #hue = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        #sat = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        #val = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        #cv.Split(proc_image, hue,sat,val, None )
        #cv.ShowImage("Hue Video", hue)
        #cv.ShowImage("Saturation Video", sat)
        #cv.ShowImage("Value Video", val)

        thresh_0 = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        thresh_1 = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        thresh_2 = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        red_orange = cv.CreateMat(input_image.rows,input_image.cols,cv.CV_8UC1)
        cv.Threshold(split_image[1],thresh_0, 128,255,cv.CV_THRESH_BINARY) # > 50% saturation
        cv.Threshold(split_image[0],thresh_1, 220,255,cv.CV_THRESH_BINARY) # > Purple
        cv.Threshold(split_image[0],thresh_2, 10, 255,cv.CV_THRESH_BINARY_INV) # < Yellow-Orange
        cv.Add(thresh_1,thresh_2,red_orange)
        cv.And(red_orange,thresh_0,red_orange)
        cv.ShowImage("Red-Orange Video",red_orange)

        cv.CvtColor(blur_image, proc_image, cv.CV_BGR2HLS)
        cv.Split(proc_image, split_image[0], split_image[1],split_image[2], None )
        cv.Threshold(split_image[1],thresh_0, 204,255,cv.CV_THRESH_BINARY) # > 80% Lum
        cv.ShowImage("White Video",thresh_0)
        cv.Or(red_orange, thresh_0, thresh_0)
        cv.ShowImage("Red-Orange and White Video",thresh_0)
        cv.WaitKey(30)

        ang_z = 0
        x = 0
        for i in range(input_image.rows):
            y = -(input_image.cols / 2)
            row = cv.GetRow(thresh_0,i)
            for j in row.tostring():
                ang_z = ang_z + (x * y *ord(j))
                y = y + 1
            x = x + 1
        ang_z = (ang_z * pi * 2 * 2 * 4 / 255 / input_image.rows / input_image.rows / input_image.cols / input_image.cols)
        p = Twist()
        p.linear.x = self.speed
        p.angular.z = ang_z
        self.pub.publish(p)
Beispiel #11
0
    def show(self):
        """ Process and show the current frame """
        source = cv.LoadImage(self.files[self.index])
        width, height = cv.GetSize(source)

        center = (width / 2) + self.offset

        cv.Line(source, (center, 0), (center, height), (0, 255, 0), 1)

        mask = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)

        if self.roi:
            red = cv.CreateImage((width, height), cv.IPL_DEPTH_8U, 1)

            cv.Zero(mask)
            cv.Split(source, None, None, red, None)
            cv.InRangeS(red, self.thresholdMin, self.thresholdMax, red)
            cv.Copy(red, mask)

            x, y, x1, y1 = self.roi

            width = x1 - x
            height = y1 - y

            cv.Rectangle(source, (int(x), int(y)), (int(x1), int(y1)),
                         (255.0, 255, 255, 0))

            cv.SetImageROI(source, (x, y, width, height))
            cv.SetImageROI(red, (x, y, width, height))

            tmp = cv.CreateImage(cv.GetSize(red), cv.IPL_DEPTH_8U, 1)
            cv.Zero(tmp)
            cv.Copy(red, tmp)

            line = []
            points = []

            #cv.ShowImage('red',tmp);

            step = 1

            for i in range(0, height - 1):
                row = cv.GetRow(tmp, i)
                minVal, minLoc, maxLoc, maxVal = cv.MinMaxLoc(row)

                y = i
                x = maxVal[0]
                point = (0, 0, 0)

                if x > 0:
                    line.append((x, y))

                    s = x / sin(self.camAngle)
                    x = s * cos(self.angles[self.index])
                    z = y / 2.0
                    y = s * sin(self.angles[self.index])
                    point = (x, y, z)

                points.append(point)

            cv.PolyLine(source, [line], False, (255, 0, 0), 2, 8)

            cv.ResetImageROI(red)
            cv.ResetImageROI(source)

        if self.mode == 'mask':
            cv.ShowImage('preview', mask)
            return

        if self.mode == 'record' and self.roi:
            font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 1)
            cv.PutText(source, "recording %d" % self.index, (20, 20), font,
                       (0, 0, 255))
            self.points.extend(points)
            #self.colors.extend(colors);

        cv.ShowImage('preview', source)
Beispiel #12
0
    def show( self ):
        """ Process and show the current frame """
        source  = cv.LoadImage( self.files[self.index] )
        width, height = cv.GetSize(source)
        
        center = (width/2) + self.offset;
        
        cv.Line( source, (center,0), (center,height), (0,255,0), 1)


        if self.roi:
            x,y,a,b = self.roi;
            
            width, height = ((a - x), (b - y))
            mask = cv.CreateImage( (width, height), cv.IPL_DEPTH_8U, 1)
        
            cv.SetImageROI( source, (x, y, width, height))           
            cv.Split( source, None, None, mask, None );
            
            gray = cv.CloneImage( mask );
        
            cv.InRangeS( mask, self.thresholdMin, self.thresholdMax, mask );
            cv.And( mask, gray, gray );            
        
            line    = [];
            points  = []; 
        
            for i in range(0,height-1):
                point   = (0, 0, 0)
                row     = cv.GetRow( gray, i)
                
                minVal,minLoc,maxLoc,maxVal = cv.MinMaxLoc(row);
                
                y = i;
                x = maxVal[0]
                
                if x > 0:
                    line.append((x,y));
        
                    s = x / sin(radians(self.camAngle))
                    x = s * cos(self.angles[self.index])                    
                    z = height - y
                    y = s * sin(self.angles[self.index])
                    
                    point = (round(x,2),round(y,2),z);
                
                points.append(point)
        
        
            cv.PolyLine( source, [line], False, (255,0,0), 2, 8)
            cv.ResetImageROI( source )
            x,y,a,b = self.roi;
            cv.Rectangle( source, (int(x), int(y)), (int(a), int(b)), (255.0, 255, 255, 0) );

        if self.roi:
            x,y,a,b = self.roi;
            
            width, height = ((a - x), (b - y))
            mask = cv.CreateImage( (width, height), cv.IPL_DEPTH_8U, 1)
        
            cv.SetImageROI( source, (x-width, y, width, height)) # moves roi to the left
            cv.Split( source, None, None, mask, None );
            
            gray = cv.CloneImage( mask );
        
            cv.InRangeS( mask, self.thresholdMin, self.thresholdMax, mask );
            cv.And( mask, gray, gray );            
        
            line    = [];
            #points  = []; 
        
            for i in range(0,height-1):
                point   = (0, 0, 0)
                row     = cv.GetRow( gray, i)
                
                minVal,minLoc,maxLoc,maxVal = cv.MinMaxLoc(row);
                
                y = i;
                x = maxVal[0]
                
                if x > 0:
                    line.append((x,y));
                    
                    x = width - x; # left to the x-axis
        
                    s = x / sin(radians(self.camAngle))
                                        
                    x = s * cos(self.angles[self.index])                    
                    z = height - y# 500 higher then the other.
                    y = s * sin(self.angles[self.index])


                    #x' = x*cos q - y*sin q
                    #y' = x*sin q + y*cos q
                    #z' = z
                    
                    a = radians(300)
                    
                    nx = ( cos(a) * x ) - ( sin(a) * y )
                    ny = ( sin(a) * x ) + ( cos(a) * y )
                    
                    point = (nx,ny,z);
                
                #if point[0] != 0:
                #    points[i] = point;
                
                points.append(point)
                
            cv.PolyLine( source, [line], False, (255,0,0), 2, 8)
            cv.ResetImageROI( source )
            x,y,a,b = self.roi;
            cv.Rectangle( source, (int(x), int(y)), (int(a), int(b)), (255.0, 255, 255, 0) );


        #if self.roi:
        #    x,y,a,b = self.roi;
        #    
        #    width, height = ((a - x), (b - y))
        #    
        #    roi = [x-width, y, x, b];
        #    
        #    x,y,a,b = roi;
        #    
        #    
        #    mask = cv.CreateImage( (width, height), cv.IPL_DEPTH_8U, 1)
        #
        #    cv.SetImageROI( source, (x, y, width, height))           
        #    cv.Split( source, None, None, mask, None );
        #    
        #    gray = cv.CloneImage( mask );
        #
        #    cv.InRangeS( mask, self.thresholdMin, self.thresholdMax, mask );
        #    cv.And( mask, gray, gray );            
        #    cv.ShowImage('tmp', gray)
        #
        #    line    = [];
        #    #points  = []; 
        #
        #    for i in range(0,height-1):
        #        point   = (0, 0, 0)
        #        row     = cv.GetRow( gray, i)
        #        
        #        minVal,minLoc,maxLoc,maxVal = cv.MinMaxLoc(row);
        #        
        #        y = i;
        #        x = maxVal[0]
        #        
        #        if x > 0:
        #            line.append((x,y));
        #            
        #            x = x - width
        #
        #            s = x / sin(-330)
        #            x = s * cos(self.angles[self.index])                    
        #            z = y/2.0
        #            y = s * sin(self.angles[self.index])
        #            
        #            point = (x,y,z);
        #        
        #        points.append(point)
        #
        #
        #    cv.PolyLine( source, [line], False, (255,0,0), 2, 8)
        #    cv.ResetImageROI( source )
        #    x,y,a,b = self.roi;
        #    
        #    cv.Rectangle( source, (roi[0], roi[1]), (roi[2], roi[3]), (255.0, 255, 255, 0) );
        #
        if self.mode == 'mask':
            cv.ShowImage( 'preview', mask )
            return

        if self.mode == 'record' and self.roi:
            font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX,0.5,0.5,1)
            cv.PutText( source, "recording %d" % self.index, (20,20), font, (0,0,255))
            self.points.extend(points);
            #self.colors.extend(colors);



        cv.ShowImage( 'preview', source )