コード例 #1
0
    def run(self):
        started = time.time()
        while True:

            curframe = cv.QueryFrame(self.capture)
            instant = time.time()  #Get timestamp o the frame

            self.processImage(curframe)  #Process the image

            if not self.isRecording:
                if self.somethingHasMoved():
                    self.trigger_time = instant  #Update the trigger_time
                    if instant > started + 5:  #Wait 5 second after the webcam start for luminosity adjusting etc..
                        print("Something is moving !")
                        if self.doRecord:  #set isRecording=True only if we record a video
                            self.isRecording = True
            else:
                if instant >= self.trigger_time + 10:  #Record during 10 seconds
                    print("Stop recording")
                    self.isRecording = False
                else:
                    cv.PutText(curframe,
                               datetime.now().strftime("%b %d, %H:%M:%S"),
                               (25, 30), self.font, 0)  #Put date on the frame
                    cv.WriteFrame(self.writer, curframe)  #Write the frame

            if self.show:
                cv.ShowImage("Image", curframe)
                cv.ShowImage("Res", self.res)

            cv.Copy(self.frame2gray, self.frame1gray)
            c = cv.WaitKey(1)
            if c == 27 or c == 1048603:  #Break if user enters 'Esc'.
                break
コード例 #2
0
def getIris(frame):
	iris = []
	copyImg = cv.CloneImage(frame)
	resImg = cv.CloneImage(frame)
	grayImg = cv.CreateImage(cv.GetSize(frame), 8, 1)
	mask = cv.CreateImage(cv.GetSize(frame), 8, 1)
	storage = cv.CreateMat(frame.width, 1, cv.CV_32FC3)
	cv.CvtColor(frame,grayImg,cv.CV_BGR2GRAY)
	cv.Canny(grayImg, grayImg, 5, 70, 3)
	cv.Smooth(grayImg,grayImg,cv.CV_GAUSSIAN, 7, 7)
	circles = getCircles(grayImg)
	iris.append(resImg)
	for circle in circles:
		rad = int(circle[0][2])
		global radius
		radius = rad
		cv.Circle(mask, centroid, rad, cv.CV_RGB(255,255,255), cv.CV_FILLED)
		cv.Not(mask,mask)
		cv.Sub(frame,copyImg,resImg,mask)
		x = int(centroid[0] - rad)
		y = int(centroid[1] - rad)
		w = int(rad * 2)
		h = w
		cv.SetImageROI(resImg, (x,y,w,h))
		cropImg = cv.CreateImage((w,h), 8, 3)
		cv.Copy(resImg,cropImg)
		cv.ResetImageROI(resImg)
		return(cropImg)
	return (resImg)
コード例 #3
0
    def found_face(self):
        # global frame_copy
        if (not self.camera_is_on()) or (not self.find_face_is_on()):
            return False

        self.flushCameraBuffer()  # this reduces the frame delay
        frame = cv.QueryFrame(self.capture)
        if frame is None:
            self.close_camera()
            return False

        if not frame:
            cv.WaitKey(0)
        if not self.frame_copy:
            self.frame_copy = cv.CreateImage((frame.width, frame.height),
                                             cv.IPL_DEPTH_8U, frame.nChannels)

        if frame.origin == cv.IPL_ORIGIN_TL:
            cv.Copy(frame, self.frame_copy)
        else:
            cv.Flip(frame, self.frame_copy, 0)

        if self.showVideo:
            result = self.detect_and_draw(self.frame_copy)
        else:
            result = self.detect_no_draw(self.frame_copy)
        cv.WaitKey(10)
        return result
コード例 #4
0
 def _build_image(self, frame):
     if not self._frame:
         self._frame = cv2.CreateImage((frame.width, frame.height), cv.IPL_DEPTH_8U, frame.nChannels)
     if frame.origin == cv2.IPL_ORIGIN_TL:
         cv2.Copy(frame, self._frame)
     else:
         cv2.Flip(frame, self._frame, 0)
     return IplQImage(self._frame)
コード例 #5
0
 def draw_model_fitter(f):
   cv.NamedWindow("Model Fitter", cv.CV_WINDOW_AUTOSIZE)
   # Copy image
   i = cv.CreateImage(cv.GetSize(f.image), f.image.depth, 3)
   cv.Copy(f.image, i)
   for pt_num, pt in enumerate(f.shape.pts):
     # Draw normals
     cv.Circle(i, (int(pt.x), int(pt.y)), 2, (0,0,0), -1)
   cv.ShowImage("Shape Model",i)
   cv.WaitKey()
コード例 #6
0
    def getSegments(self, image):
        """
        segmentize the region of interest into segments, each containing a mean value
        """

        left, top, width, height = self.regionOfInterest

        #create a new image containing just the distances in the region of interest
        imageDepth = image.depth
        imageChannels = image.nChannels
        regionDistances = cv.CreateImage((width, height), imageDepth,
                                         imageChannels)
        src_region = cv.GetSubRect(image, (left, top, width, height))
        cv.Copy(src_region, regionDistances)

        #segmentize the distances into segments
        segments = self.segmentize(regionDistances)

        return segments
コード例 #7
0
lwpImg = cv.imread(path)
# 创建图像空间,参数为size, depth, channels,这里设置的是图片等高宽30个像素的一个区域,8位,灰度图
# box_lwpImg = cv.create((30, 576), 8, 1)   # cv2 中没有 create方法了,用np.zeros 创建矩阵
box_lwpImg = np.zeros((30, 576), dtype=np.uint8)

# 创建窗口
cv.namedWindow('test1', cv.WINDOW_AUTOSIZE)
cv.namedWindow("box_test1", cv.WINDOW_AUTOSIZE)
'''
# 设置ROI区域,即感兴趣区域,参数为x, y, width, heigh
cv.setImageROI(lwpImg, (390, 0, 30, 576))  # 老版本使用

cv2 利用numpy中的数组切片 设置ROI区域
'''
roiImg = lwpImg[390:0, 576:30]
'''
# 提取ROI,从lwpImg图片的感兴趣区域到box_lwpImg
cv.Copy(lwpImg, box_lwpImg)
cv.copy 方法已经不用了
'''

# 对box区域进行循环提取像素值存到列表pixel_list中
pixel_list = []
for i in range(30):  # 576为box的高
    for j in range(576):  # 30为box的宽
        x = box_lwpImg[i, j]
        pixel_list.append(x)

# 提取的像素值转为int整型赋给一维数组pixel_list_np_1
pixel_list_np_1 = np.array(pixel_list, dtype=int)
# 转为576*30的二位数组,即按图片box排列
コード例 #8
0
  def __get_max_along_normal(self, p_num, scale):
    """ Gets the max edge response along the normal to a point

    :param p_num: Is the number of the point in the shape
    """

    norm = self.shape.get_normal_to_point(p_num)
    p = self.shape.pts[p_num]

    # Find extremes of normal within the image
    # Test x first
    min_t = -p.x / norm[0]
    if p.y + min_t*norm[1] < 0:
      min_t = -p.y / norm[1]
    elif p.y + min_t*norm[1] > self.image.height:
      min_t = (self.image.height - p.y) / norm[1]

    # X first again
    max_t = (self.image.width - p.x) / norm[0]
    if p.y + max_t*norm[1] < 0:
      max_t = -p.y / norm[1]
    elif p.y + max_t*norm[1] > self.image.height:
      max_t = (self.image.height - p.y) / norm[1]

    # Swap round if max is actually larger...
    tmp = max_t
    max_t = max(min_t, max_t)
    min_t = min(min_t, tmp)

    # Get length of the normal within the image
    x1 = min(p.x+max_t*norm[0], p.x+min_t*norm[0])
    x2 = max(p.x+max_t*norm[0], p.x+min_t*norm[0])
    y1 = min(p.y+max_t*norm[1], p.y+min_t*norm[1])
    y2 = max(p.y+max_t*norm[1], p.y+min_t*norm[1])
    l = math.sqrt((x2-x1)**2 + (y2-y1)**2)

    img = cv.CreateImage(cv.GetSize(self.image), self.g_image[scale].depth, 1)
    cv.Copy(self.g_image[scale], img)
    #cv.Circle(img, \
    #    (int(norm[0]*min_t + p.x), int(norm[1]*min_t + p.y)), \
    #    5, (0, 0, 0))
    #cv.Circle(img, \
    #    (int(norm[0]*max_t + p.x), int(norm[1]*max_t + p.y)), \
    #    5, (0, 0, 0))

    # Scan over the whole line
    max_pt = p
    max_edge = 0

    # Now check over the vector
    #v = min(max_t, -min_t)
    #for t in drange(min_t, max_t, (max_t-min_t)/l):
    search = 20+scale*10
    # Look 6 pixels to each side too
    for side in range(-6, 6):
      # Normal to normal...
      new_p = Point(p.x + side*-norm[1], p.y + side*norm[0])
      for t in drange(-search if -search > min_t else min_t, \
                       search if search < max_t else max_t , 1):

        x = int(norm[0]*t + new_p.x)
        y = int(norm[1]*t + new_p.y)
        if x < 0 or x > self.image.width or y < 0 or y > self.image.height:
          continue
#        cv.Circle(img, (x, y), 3, (100,100,100))
        #print x, y, self.g_image.width, self.g_image.height
        if self.g_image[scale][y-1, x-1] > max_edge:
          max_edge = self.g_image[scale][y-1, x-1]
          max_pt = Point(new_p.x + t*norm[0], new_p.y + t*norm[1])

#    for point in self.shape.pts:
#      cv.Circle(img, (int(point.x), int(point.y)), 3, (255,255,255))
##
#    cv.Circle(img, (int(max_pt.x), int(max_pt.y)), 3, (255,255,255))
##
#    cv.NamedWindow("Scale", cv.CV_WINDOW_AUTOSIZE)
#    cv.ShowImage("Scale",img)
#    cv.WaitKey()
#
    return max_pt
コード例 #9
0
ファイル: gui.py プロジェクト: lovethegirl/opencv
def CamGui():
    capture = cv.VideoCapture(0)
    width = int(capture.get(cv.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv.CAP_PROP_FRAME_HEIGHT))
    prev_gray = cv.CreateImage((width, height), 8, 1)
    gray = cv.CreateImage((width, height), 8, 1)

    # Will hold the pyr frame at t-1
    prevPyr = cv.CreateImage((height / 3, width + 8), 8, cv.CV_8UC1)
    currPyr = cv.CreateImage((height / 3, width + 8),
                             8, cv.CV_8UC1)  # idem at t

    max_count = 500
    qLevel = 0.01
    minDist = 10
    prev_points = []  # Points at t-1
    curr_points = []  # Points at t
    lines = []  # To keep all the lines overtime

    while True:
        frame = cv.QueryFrame(capture)
        cv.CvtColor(frame, gray, cv.CV_BGR2GRAY)  # Convert to gray
        output = cv.CloneImage(frame)

        prev_points = cv.GoodFeaturesToTrack(
            gray, None, None, max_count, qLevel, minDist)
        curr_points, status, err = cv.CalcOpticalFlowPyrLK(
            prev_gray, gray, prevPyr, currPyr, prev_points, (10, 10), 3, (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03), 0)

        # If points status are ok and distance not negligible keep the point
        k = 0
        for i in range(len(curr_points)):
            nb = abs(int(prev_points[i][0]) - int(curr_points[i][0])) + \
                abs(int(prev_points[i][1]) - int(curr_points[i][1]))
            if status[i] and nb > 2:
                prev_points[k] = prev_points[i]
                curr_points[k] = curr_points[i]
                k += 1

        prev_points = prev_points[:k]
        curr_points = curr_points[:k]
        # At the end only interesting points are kept

        # Draw all the previously kept lines otherwise they would be lost the next frame
        for (pt1, pt2) in lines:
            cv.Line(frame, pt1, pt2, (255, 255, 255))

        # Draw the lines between each points at t-1 and t
        for prevpoint, point in zip(prev_points, curr_points):
            prevpoint = (int(prevpoint[0]), int(prevpoint[1]))
            cv.Circle(frame, prevpoint, 15, 0)
            point = (int(point[0]), int(point[1]))
            cv.Circle(frame, point, 3, 255)
            cv.Line(frame, prevpoint, point, (255, 255, 255))
            # Append current lines to the lines list
            lines.append((prevpoint, point))

        cv.Copy(gray, prev_gray)  # Put the current frame prev_gray
        prev_points = curr_points

        cv.ShowImage("The Video", frame)
        #cv.WriteFrame(writer, frame)
        c = cv.WaitKey(1)
        if c == 27:  # Esc on Windows
            break