예제 #1
0
def main():
    os.chdir(sys.argv[1])
    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except OSError:
        pass

    tree = et.parse("project.xml")

    movie = tree.getroot()
    file_path = movie.attrib["path"]

    if DEBUG:
        cv.NamedWindow("win", cv.CV_WINDOW_AUTOSIZE)
        cv.MoveWindow("win", 200, 200)

    cap = cv.CreateFileCapture(file_path)
    skip_frames(cap, movie)

    pixel_count = None
    prev_img = None

    global_frame_counter = 0
    file_counter = 0

    w = None
    h = None

    output_img = cv.CreateImage((WIDTH, MAX_FRAMES), cv.IPL_DEPTH_8U, 3)

    f = open("shots.txt", "r")
    lines = [line for line in f if line]  # (start_frame, end_frame, duration)
    f.close()

    f_frm = open("motion.txt", "w")
    f_avg = open("motion_shot-avg.txt", "w")
    motion = []

    t = time.time()

    for nr, line in enumerate(lines):
        print(nr + 1), "/", len(lines)

        duration = int(line.split("\t")[2])

        for frame_counter in range(duration):
            img = cv.QueryFrame(cap)
            if not img:
                print "error?"
                print nr, frame_counter
                #break
                return

            if DEBUG:
                cv.ShowImage("win", img)

            global_frame_counter += 1

            if nr == 0 and frame_counter == 0:  # first shot, first frame
                w = img.width
                h = img.height
                pixel_count = float(img.width * img.height)
                prev_img = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
                cv.Zero(prev_img)

            diff = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
            cv.AbsDiff(img, prev_img, diff)
            cv.Threshold(diff, diff, 10, 255, cv.CV_THRESH_BINARY)
            d_color = 0
            for i in range(1, 4):
                cv.SetImageCOI(diff, i)
                d_color += cv.CountNonZero(diff) / pixel_count
            d_color = d_color / 3  # 0..1
            #print "%.1f" % (d_color*100), "%"

            motion.append(d_color)
            cv.Copy(img, prev_img)

            # WRITE TEXT FILE
            f_frm.write("%f\n" % (d_color))
            if frame_counter == duration - 1:  # last frame of current shot
                motion_value = sum(motion) / len(motion)
                print "average motion:", motion_value
                f_avg.write("%f\t%d\n" % (motion_value, duration))
                motion = []

            # WRITE IMAGE
            if frame_counter == 0:  # ignore each first frame -- the diff after a hard cut is meaningless
                global_frame_counter -= 1
                continue
            else:
                for i in range(WIDTH):
                    value = d_color * 255
                    cv.Set2D(output_img,
                             (global_frame_counter - 1) % MAX_FRAMES, i,
                             cv.RGB(value, value, value))

            if global_frame_counter % MAX_FRAMES == 0:
                cv.SaveImage(
                    os.path.join(OUTPUT_DIR_NAME,
                                 "motion_%03d.png" % (file_counter)),
                    output_img)
                file_counter += 1

            if DEBUG:
                if cv.WaitKey(1) == 27:
                    break

    if global_frame_counter % MAX_FRAMES != 0:
        #cv.SetImageROI(output_img, (0, 0, WIDTH-1, (global_frame_counter % MAX_FRAMES)-1))
        cv.SetImageROI(output_img, (0, 0, WIDTH - 1,
                                    (global_frame_counter - 1) % MAX_FRAMES))
        cv.SaveImage(
            os.path.join(OUTPUT_DIR_NAME, "motion_%03d.png" % (file_counter)),
            output_img)

    f_frm.close()
    f_avg.close()

    if DEBUG:
        cv.DestroyWindow("win")

    print "%.2f min" % ((time.time() - t) / 60)
    #raw_input("- done -")
    return
예제 #2
0
    cv.PutText(image, "Particle Filter " + str(mu_x), pt1, font,
               cv.CV_RGB(255, 255, 0))


if __name__ == "__main__":

    snap_no = 0
    frame_no = 0

    # create windows
    cv.NamedWindow('Camera')

    # create capture device
    device = 0  # assume we want first device

    capture = cv.CreateFileCapture(sys.argv[1])
    dim = 3
    forward_step = -2.

    pts = dim * dim
    mid = int(pts / 2)

    cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
    cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

    # check if capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit(1)

    pf = PF(K, 200)
예제 #3
0
def main():
    BLACK_AND_WHITE = False
    THRESHOLD = 0.48
    BW_THRESHOLD = 0.4

    if len(sys.argv) < 2:
        print "usage: %s project_dir [bw]" % (sys.argv[0])
        return

    if len(sys.argv) > 2:
        if sys.argv[2] == "bw":
            BLACK_AND_WHITE = True
            THRESHOLD = BW_THRESHOLD
            print " B/W MODE"

    tree = utils.open_project(sys.argv, False)
    if tree == None:
        return

    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except:
        pass

    movie = tree.getroot()
    file_path = movie.attrib["path"]
    cap = cv.CreateFileCapture(file_path)

    if DEBUG:
        cv.NamedWindow("win", cv.CV_WINDOW_AUTOSIZE)
        cv.MoveWindow("win", 200, 200)

    hist = None
    prev_hist = None
    prev_img = None

    pixel_count = None
    frame_counter = 0

    last_frame_black = False
    black_frame_start = -1

    t = time.time()

    while 1:
        img_orig = cv.QueryFrame(cap)

        if not img_orig:  # eof
            output_file = os.path.join(OUTPUT_DIR_NAME,
                                       "%06d.png" % (frame_counter - 1))
            cv.SaveImage(output_file, prev_img)
            """movie.set("frames", str(frame_counter))
			tree.write("project.xml")"""
            break

        img = cv.CreateImage(
            (int(img_orig.width / 4), int(img_orig.height / 4)),
            cv.IPL_DEPTH_8U, 3)
        cv.Resize(img_orig, img, cv.CV_INTER_AREA)

        if frame_counter == 0:  # erster frame
            cv.SaveImage(os.path.join(OUTPUT_DIR_NAME, "%06d.png" % (0)), img)
            pixel_count = img.width * img.height
            prev_img = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
            cv.Zero(prev_img)

        if DEBUG and frame_counter % 2 == 1:
            cv.ShowImage("win", img)

        img_hsv = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
        cv.CvtColor(img, img_hsv, cv.CV_BGR2HSV)

        # #####################
        # METHOD #1: find the number of pixels that have (significantly) changed since the last frame
        diff = cv.CreateImage(cv.GetSize(img), cv.IPL_DEPTH_8U, 3)
        cv.AbsDiff(img_hsv, prev_img, diff)
        cv.Threshold(diff, diff, 10, 255, cv.CV_THRESH_BINARY)
        d_color = 0
        for i in range(1, 4):
            cv.SetImageCOI(diff, i)
            d_color += float(cv.CountNonZero(diff)) / float(pixel_count)

        if not BLACK_AND_WHITE:
            d_color = float(d_color / 3.0)  # 0..1

        # #####################
        # METHOD #2: calculate the amount of change in the histograms
        h_plane = cv.CreateMat(img.height, img.width, cv.CV_8UC1)
        s_plane = cv.CreateMat(img.height, img.width, cv.CV_8UC1)
        v_plane = cv.CreateMat(img.height, img.width, cv.CV_8UC1)
        cv.Split(img_hsv, h_plane, s_plane, v_plane, None)
        planes = [h_plane, s_plane, v_plane]

        hist_size = [50, 50, 50]
        hist_range = [[0, 360], [0, 255], [0, 255]]
        if not hist:
            hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, hist_range, 1)
        cv.CalcHist([cv.GetImage(i) for i in planes], hist)
        cv.NormalizeHist(hist, 1.0)

        if not prev_hist:
            prev_hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, hist_range,
                                      1)
            # wieso gibt es kein cv.CopyHist()?!
            cv.CalcHist([cv.GetImage(i) for i in planes], prev_hist)
            cv.NormalizeHist(prev_hist, 1.0)
            continue

        d_hist = cv.CompareHist(prev_hist, hist, cv.CV_COMP_INTERSECT)

        # combine both methods to make a decision
        if ((0.4 * d_color + 0.6 * (1 - d_hist))) >= THRESHOLD:
            if DEBUG:
                if frame_counter % 2 == 0:
                    cv.ShowImage("win", img)
                #winsound.PlaySound(soundfile, winsound.SND_FILENAME|winsound.SND_ASYNC)
            print "%.3f" % ((0.4 * d_color + 0.6 * (1 - d_hist))), "%.3f" % (
                d_color), "%.3f" % (1 - d_hist), frame_counter
            if DEBUG and DEBUG_INTERACTIVE:
                #if win32api.MessageBox(0, "cut?", "", win32con.MB_YESNO) == 6: #yes
                #	cv.SaveImage(OUTPUT_DIR_NAME + "\\%06d.png" % (frame_counter), img)
                pass
            else:
                cv.SaveImage(OUTPUT_DIR_NAME + "\\%06d.png" % (frame_counter),
                             img)

        cv.CalcHist([cv.GetImage(i) for i in planes], prev_hist)
        cv.NormalizeHist(prev_hist, 1.0)

        # #####################
        # METHOD #3: detect series of (almost) black frames as an indicator for "fade to black"
        average = cv.Avg(v_plane)[0]
        if average <= 0.6:
            if not last_frame_black:  # possible the start
                print "start", frame_counter
                black_frame_start = frame_counter
            last_frame_black = True
        else:
            if last_frame_black:  # end of a series of black frames
                cut_at = black_frame_start + int(
                    (frame_counter - black_frame_start) / 2)
                print "end", frame_counter, "cut at", cut_at
                img_black = cv.CreateImage(
                    (img_orig.width / 4, img_orig.height / 4), cv.IPL_DEPTH_8U,
                    3)
                cv.Set(img_black, cv.RGB(0, 255, 0))
                cv.SaveImage(OUTPUT_DIR_NAME + "\\%06d.png" % (cut_at),
                             img_black)
            last_frame_black = False

        cv.Copy(img_hsv, prev_img)
        frame_counter += 1

        if DEBUG:
            if cv.WaitKey(1) == 27:
                break

    if DEBUG:
        cv.DestroyWindow("win")

    print "%.2f min" % ((time.time() - t) / 60)
    #raw_input("- done -")
    return
예제 #4
0
def main():

    tree = utils.open_project(sys.argv)
    if tree == None:
        return

    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except OSError:
        pass

    movie = tree.getroot()
    file_path = movie.attrib["path"]

    cap = cv.CreateFileCapture(file_path)
    cv.QueryFrame(cap)

    # skip frames in the beginning, if neccessary
    start_frame = int(movie.attrib["start_frame"])
    for i in range(start_frame):
        cv.QueryFrame(cap)

    f = open("shots.txt", "r")
    lines = [line for line in f if line]
    f.close()

    t = time.time()

    w = None
    h = None

    #for line in f:
    for nr, line in enumerate(lines):
        print(nr + 1), "/", len(lines)

        #frame_from, frame_to, width, scene_nr = [int(i) for i in line.split("\t")]
        #width, scene_nr = [int(i) for i in line.split("\t")][2:]
        start_frame, end_frame, width = [
            int(splt) for splt in line.split("\t")
        ]
        #width *= STRETCH_FAKTOR

        faktor = None
        output_img = None

        for frame_counter in range(width):
            #if frame_counter % STRETCH_FAKTOR == 0:
            #	img = cv.QueryFrame(cap)
            #	if not img:
            #		break

            img = cv.QueryFrame(cap)
            if not img:
                break

            if nr == 0:
                w = img.width
                h = img.height

            if frame_counter == 0:
                faktor = float(w) / float(width)
                output_img = cv.CreateImage((width, h), cv.IPL_DEPTH_8U, 3)

            col_nr = faktor * (frame_counter + 0.5)
            col_nr = int(math.floor(col_nr))
            #print frame_counter, width, col_nr, w
            col = cv.GetCol(img, col_nr)

            for i in range(h):
                cv.Set2D(output_img, i, frame_counter, cv.Get1D(col, i))

        #return

        cv.SaveImage(
            os.path.join(OUTPUT_DIR_NAME,
                         "shot_slitscan_%03d_%d.png" % (nr + 1, start_frame)),
            output_img)

    print "%.2f min" % ((time.time() - t) / 60)
    #raw_input("- done -")
    return
예제 #5
0
파일: test1.py 프로젝트: wy51r/kod
if __name__ == "__main__":

    tree = {}

    snap_no = 0
    print "Press ESC to quit, 't' to take a picture (image will be "
    print "saved in a snap.jpg file"

    # create windows
    cv.NamedWindow('Camera')

    # create capture device
    device = 0  # assume we want first device

    capture = cv.CreateFileCapture(
        "/home/burak/Dropbox/Public/skfiles/campy/chessb-left.avi")
    #capture = cv.CreateCameraCapture (0)

    cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
    cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

    # check if capture device is OK
    if not capture:
        print "Error opening capture device"
        sys.exit(1)

    # fast forward
    frame_no = 0
    while (frame_no < __start__):
        frame = cv.QueryFrame(capture)
        frame_no += 1
예제 #6
0
''' 
Referred to example 2.1 in the book "Learning OpenCV: Computer Vision with the OpenCV Library"

Example 2-2. A simple OpenCV program for playing a video file from disk.

Brought to you by Abid.K	--mail me at [email protected]
'''
################################################################################################
import cv
cv.NamedWindow("Example2", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CreateFileCapture(
    "video.avi")  #cv.CreateFileCapture(video_file_path)
while (1):
    frame = cv.QueryFrame(capture)
    cv.ShowImage("Example2", frame)
    c = cv.WaitKey(33)
    if c == 1048603:  #cv.WaitKey(33) waits for 33 ms.If a keystroke comes in that time, it is stored in
        break  #variable c. If c=1048603,which corresponds to Esc key, window is destroyed.
cv.DestroyWindow("Example2")
#################################################################################################
# 33 ms is calculated on assumption that around 30 frames are shown in a second. If you want to play video faster, just reduce that time. To play it slower, increase the time.
예제 #7
0
    bgfn = sys.argv[2]

#corners = [[259, 117], [720, 98], \
#        [725, 567], [268, 567]]  # clockwise from top left
corners = [[300, 65], [760, 73], \
        [732, 528], [291, 505]]

start_frame = 160

corners = np.array(corners)
mazebb = np.array([[np.min(corners[:, 0]), np.min(corners[:, 1])], \
        [np.max(corners[:, 0]), np.max(corners[:, 1])]])
mazexbb = [mazebb[0, 0], mazebb[1, 0]]
mazeybb = [mazebb[0, 1], mazebb[1, 1]]

cap = cv.CreateFileCapture(fn)
width = int(np.round(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_WIDTH)))
height = int(np.round(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_HEIGHT)))
size = (int(width), int(height))
logging.debug("Frame size: %i %i" % size)
#cv.SetCaptureProperty(cap, cv.CV_CAP_PROP_POS_AVI_RATIO, 1.0)
#nframes = int(np.round(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_POS_FRAMES)))
#cv.SetCaptureProperty(cap, cv.CV_CAP_PROP_POS_AVI_RATIO, 0.0)
# doesn't seem to work:
nframes = int(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_COUNT))
logging.debug("NFrames: %i" % nframes)

# make scratch images
gim = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
fgim = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
fim = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
예제 #8
0
#! /usr/bin/env python

import cv

cap = cv.CreateFileCapture("../c/tree.avi")
img = cv.QueryFrame(cap)
print "Got frame of dimensions (", img.width, " x ", img.height, ")"

cv.NamedWindow("win", cv.CV_WINDOW_AUTOSIZE)
cv.ShowImage("win", img)
cv.MoveWindow("win", 200, 200)
cv.WaitKey(0)
예제 #9
0
def main():
	global startframe

	tree = utils.open_project(sys.argv)
	if tree == None:
		return

	os.chdir("shot_slitscans")

	'''cv.NamedWindow("win", cv.CV_WINDOW_AUTOSIZE)
	cv.MoveWindow("win", 500, 200)
	cv.SetMouseCallback("win", mouse_callback)'''

	bg_img = cv.CreateImage((576, 576), cv.IPL_DEPTH_8U, 1)
	#cv.Set(bg_img, (180))

	files = sorted( glob.glob("*.png") )
	print(files)

	i = 0
	while i < len(files):
		file = files[i]
		startframe = int( file.split("_")[3].split(".")[0] )
		print(startframe)

		cap = cv.CreateFileCapture(file)
		img = cv.QueryFrame(cap)

		win_name = "%d" % (int(float(i+1)*100.0/len(files))) + "% - " + file
		cv.NamedWindow(win_name, cv.CV_WINDOW_AUTOSIZE)
		cv.MoveWindow(win_name, 500, 200)
		cv.SetMouseCallback(win_name, mouse_callback)

		cv.ShowImage(win_name, bg_img)
		cv.ShowImage(win_name, img)

		key = cv.WaitKey(0)
		print(key)
		if key in [65363]: # right arrow
			i += 1
		elif key in [65361]: # left arrow
			i -= 1
			if i < 0:
				i = 0
		elif key in [27, 1048603]: # ESC
			break
		elif key in [65365]: # page up
			i -= 100
			if i < 0:
				i = 0
		elif key in [65366]: # page down
			i += 100
		else:
			print("Unknown key code: {}".format(key))

		cv.DestroyWindow(win_name)

	#print("System input arguments: " + sys.argv[0] + " " + sys.argv[1])
	os.chdir("/vagrant") # Now that we're using Vagrant to wrapup everything, this should work to get to the root of the project directory
	#os.system("ls -a")
	os.system("python 02_2_save-shots.py \"" + sys.argv[1] + "\"")
예제 #10
0
 def __init__(self, source=None, size=None, backend=None):
     if not opencv_available:
         raise ImportError("Opencv 2.0+ required")
     self.source = source
     self.capture = cv.CreateFileCapture(self.source)
     self.size = size
예제 #11
0
def main():
    if len(sys.argv) == 1:
        print 'Usage: %s [inputfile]' % sys.argv[0]
        sys.exit(1)

    # initialize window
    cv.NamedWindow('video', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('video', 10, 10)

    cv.NamedWindow('threshold', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('threshold', 10, 500)

    cv.NamedWindow('flow', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('flow', 500, 10)

    cv.NamedWindow('edges', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('edges', 500, 500)

    cv.NamedWindow('combined', cv.CV_WINDOW_AUTOSIZE)
    cv.MoveWindow('combined', 1000, 10)

    capture = cv.CreateFileCapture(sys.argv[1])
    if not capture:
        print 'Error opening capture'
        sys.exit(1)

    # Load bg image
    bg = cv.LoadImage('bg.png')

    # Discard some frames
    for i in xrange(2300):
        cv.GrabFrame(capture)

    frame = cv.QueryFrame(capture)
    frame_size = cv.GetSize(frame)

    # vars for playback
    fps = 25
    play = True
    velx = cv.CreateImage(frame_size, cv.IPL_DEPTH_32F, 1)
    vely = cv.CreateImage(frame_size, cv.IPL_DEPTH_32F, 1)
    combined = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    prev = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    curr = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    frame_sub = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 3)

    edges = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    prev_edges = None
    storage = cv.CreateMemStorage(0)

    blob_mask = cv0.cvCreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    cv0.cvSet(blob_mask, 1)

    hough_in = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
    hough_storage = cv.CreateMat(100, 1, cv.CV_32FC3)
    '''
    cv.CvtColor(frame, prev, cv.CV_BGR2GRAY)
    frame = cv.QueryFrame(capture)
    cv.CvtColor(frame, curr, cv.CV_BGR2GRAY)

    # winSize can't have even numbers
    cv.CalcOpticalFlowLK(prev, curr, (3,3), velx, vely)
    cv.ShowImage('video', frame)
    cv.ShowImage('flow', velx)
    cv.WaitKey(0)
    '''

    while True:

        if play:
            frame = cv.QueryFrame(capture)
            cv.Sub(frame, bg, frame_sub)
            '''#detect people
            found = list(cv.HOGDetectMultiScale(frame, storage, win_stride=(8,8),
                padding=(32,32), scale=1.05, group_threshold=2))
            for r in found:
                (rx, ry), (rw, rh) = r
                tl = (rx + int(rw*0.1), ry + int(rh*0.07))
                br = (rx + int(rw*0.9), ry + int(rh*0.87))
                cv.Rectangle(frame, tl, br, (0, 255, 0), 3)
            '''

            #color thresholding
            hsv = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 3)
            cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
            mask = cv.CreateMat(frame_size[1], frame_size[0], cv.CV_8UC1)
            cv.InRangeS(hsv, (0.06 * 256, 0.2 * 256, 0.6 * 256, 0),
                        (0.16 * 256, 1.0 * 256, 1.0 * 256, 0), mask)
            cv.ShowImage('threshold', mask)

            #optical flow method
            # store previous frame
            prev, curr = curr, prev
            # convert next frame to single channel grayscale
            cv.CvtColor(frame_sub, curr, cv.CV_BGR2GRAY)
            #cv.CalcOpticalFlowLK(prev, curr, (3,3), velx, vely)
            #cv.Threshold(velx, velx, 8.0, 0, cv.CV_THRESH_TOZERO)
            cv.CalcOpticalFlowHS(prev, curr, 1, velx, vely, 0.5,
                                 (cv.CV_TERMCRIT_ITER, 10, 0))
            cv.Threshold(velx, velx, 0.5, 0, cv.CV_THRESH_TOZERO)
            cv.Threshold(vely, vely, 0.5, 0, cv.CV_THRESH_TOZERO)
            cv.Erode(
                vely, vely,
                cv.CreateStructuringElementEx(2, 2, 0, 0, cv.CV_SHAPE_ELLIPSE))
            cv.Add(vely, velx, vely)
            cv.ShowImage('flow', vely)

            #edge detection
            cv.Canny(curr, edges, 50, 100)
            cv.Dilate(
                edges, edges,
                cv.CreateStructuringElementEx(7, 7, 0, 0, cv.CV_SHAPE_ELLIPSE))
            cv.ShowImage('edges', edges)

            if prev_edges:
                cv.CalcOpticalFlowHS(prev_edges, edges, 1, velx, vely, 0.5,
                                     (cv.CV_TERMCRIT_ITER, 10, 0))
                cv.Threshold(velx, velx, 0.5, 0, cv.CV_THRESH_TOZERO)
                cv.Threshold(vely, vely, 0.5, 0, cv.CV_THRESH_TOZERO)
                cv.ShowImage('flow', vely)
            prev_edges = edges

            cv.Threshold(vely, combined, 0.5, 255, cv.CV_THRESH_BINARY)
            cv.Min(combined, edges, combined)
            cv.ShowImage('combined', combined)

            # blobs
            myblobs = CBlobResult(edges, blob_mask, 100, False)
            myblobs.filter_blobs(10, 10000)
            blob_count = myblobs.GetNumBlobs()

            for i in range(blob_count):

                my_enumerated_blob = myblobs.GetBlob(i)
                #               print "%d: Area = %d" % (i, my_enumerated_blob.Area())
                my_enumerated_blob.FillBlob(frame,
                                            hsv2rgb(i * 180.0 / blob_count), 0,
                                            0)

            cv.ShowImage('video', frame)
            ''' crashes
            #hough transform on dilated image
            #http://wiki.elphel.com/index.php?
            # title=OpenCV_Tennis_balls_recognizing_tutorial&redirect=no
            cv.Copy(edges, hough_in)
            cv.Smooth(hough_in, hough_in, cv.CV_GAUSSIAN, 15, 15, 0, 0)
            cv.HoughCircles(hough_in, hough_storage, cv.CV_HOUGH_GRADIENT,
                            4, frame_size[1]/10, 100, 40, 0, 0)
            print hough_storage
            '''

        k = cv.WaitKey(1000 / fps)
        if k == 27:  # ESC key
            break
        elif k == 'p':  # play/pause
            play = not play
예제 #12
0
	try:
		os.mkdir(OUTPUT_DIR)
	except OSError:
		pass


	movie = tree.getroot()
	file_path = movie.attrib["path"]
<<<<<<< HEAD:02_5_100-stills.py
	#fps = float( movie.attrib["fps"] )

=======
	fps = float( movie.attrib["fps"] )
	
>>>>>>> parent of 1f8384f... minor changes:stills_100.py
	cap = cv.CreateFileCapture(file_path)
	cv.QueryFrame(cap)

	# skip frames in the beginning, if neccessary
	start_frame = int( movie.attrib["start_frame"] )
	for i in range(start_frame):
		cv.QueryFrame(cap)

	end_frame = int( movie.attrib["end_frame"] )
	every_nth_frame = int( (end_frame - start_frame) / 100 )
<<<<<<< HEAD:02_5_100-stills.py
	print("every {} frames".format(every_nth_frame))
	#print "=", every_nth_frame / fps, "sec"
=======
	print "every", every_nth_frame, "frames"
	print "=", every_nth_frame / fps, "sec"
예제 #13
0
def main():
    os.chdir(sys.argv[1])
    try:
        os.mkdir(OUTPUT_DIR_NAME)
    except:
        pass

    tree = et.parse("project.xml")
    movie = tree.getroot()
    file_path = movie.attrib["path"]
    cap = cv.CreateFileCapture(file_path)
    cv.QueryFrame(cap)

    # skip frames in the beginning, if neccessary
    start_frame = int(movie.attrib["start_frame"])
    for i in range(start_frame):
        cv.QueryFrame(cap)

    if DEBUG:
        cv.NamedWindow("win", cv.CV_WINDOW_AUTOSIZE)
        cv.MoveWindow("win", 200, 200)

    t = time.time()

    f = open("shots.txt", "r")
    scene_durations = [
        int(values[2]) for values in [line.split("\t") for line in f if line]
    ]
    f.close()

    for scene_nr, duration in enumerate(scene_durations):
        print("shot #{}/{}".format(scene_nr, len(scene_durations) - 1))

        h = int(math.ceil(float(duration) / EVERY_NTH_FRAME))
        output_img = cv.CreateImage((PIXELS_PER_COLOR * NUM_CLUSTERS, h),
                                    cv.IPL_DEPTH_8U, 3)
        frame_counter = 0

        for i in range(duration):
            img_orig = cv.QueryFrame(cap)
            if not img_orig:  # eof
                break

            if i % EVERY_NTH_FRAME != 0:
                continue

            new_width = int(img_orig.width / 4.0)
            new_height = int(img_orig.height / 4.0)

            img_small = cv.CreateImage((new_width, new_height),
                                       cv.IPL_DEPTH_8U, 3)
            cv.Resize(img_orig, img_small, cv.CV_INTER_AREA)

            if DEBUG:
                cv.ShowImage("win", img_small)

            img = cv.CreateImage((new_width, new_height), cv.IPL_DEPTH_8U, 3)
            cv.CvtColor(img_small, img, cv.CV_BGR2HLS)

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

            # set initial centroids
            init_cluster = []
            for y in [int(new_height / 4.0), int(new_height * 3 / 4.0)]:
                for x in [int(new_width * fc) for fc in [0.25, 0.75]]:
                    init_cluster.append(a[y * new_width + x])
            init_cluster.insert(
                2, a[int(new_height / 2.0) * new_width + int(new_width / 2.0)])

            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):
                #print centroids[i], count
                if count > 0:
                    centroid_count.append((centroids[i].tolist(), count))

            #centroids = centroids.tolist()
            #centroids.sort(hls_sort)

            centroid_count.sort(hls_sort2)

            px_count = new_width * new_height
            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
                    cv.Set2D(output_img, frame_counter, x + l,
                             (centroid[0], centroid[1], centroid[2]))
                x += count

            if DEBUG:
                if cv.WaitKey(1) == 27:
                    cv.DestroyWindow("win")
                    return

            frame_counter += 1

        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(
            os.path.join(OUTPUT_DIR_NAME, "shot_colors_%04d.png" % (scene_nr)),
            output_img_rgb)

    if DEBUG:
        cv.DestroyWindow("win")
    print("%.2f min" % ((time.time() - t) / 60))
    #raw_input("- done -")
    return
예제 #14
0
            y_pred = facerecognizer.clf.predict(X_test_pca)
            name = facerecognizer.category_names[y_pred[0]]

            #Draw bbox and name
            cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 1, 8, 0)
            cv.PutText(img, name, (x1, y2), font, cv.RGB(255, 0, 0))

            index += 1

    cv.ShowImage("result", img)
    return index


if __name__ == '__main__':
    input_name = sys.argv[1]
    capture = cv.CreateFileCapture(input_name)
    cv.NamedWindow("result", 1)

    frame_copy = None
    index = 0
    while index < 1000:
        frame = cv.QueryFrame(capture)
        if not frame:
            cv.WaitKey(0)
            break
        if not frame_copy:
            frame_copy = cv.CreateImage((frame.width, frame.height),
                                        cv.IPL_DEPTH_8U, frame.nChannels)
        if frame.origin == cv.IPL_ORIGIN_TL:
            cv.Copy(frame, frame_copy)
        else: