예제 #1
0
def show_detector():
    image = frame_convert.video_cv(freenect.sync_get_video()[0]);

    # cascade classifiers
    face_cascade = cv2.CascadeClassifier('opencv_data/haarcascades/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('opencv_data/haarcascades/haarcascade_eye.xml')

    # convert image to grayscale to use it with classifers
    gray = cv2.cvtColor(cv2array(image), cv2.COLOR_BGR2GRAY);

    # save previous image and use copy
    img = image;

    # detect and highlight faces
    faces = face_cascade.detectMultiScale(gray, 1.3, 5);
    for (x,y,w,h) in faces:
        cv.Rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)

    # detect and highlight eyes
    eyes = eye_cascade.detectMultiScale(gray)
    for (ex,ey,ew,eh) in eyes:
        cv.Rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    # show detector window
    cv.ShowImage('Detector', img)
예제 #2
0
def redraw():
    global draging
    global has_roi
    global roi_x0
    global roi_y0
    global cur_mouse_x
    global cur_mouse_y
    #Redraw ROI selection
    image2 = cv.CloneImage(current_image)

    # redraw old rect
    pen_width = 4
    if rect_table.has_key(current_img_file_name):
        rects_in_table = rect_table[current_img_file_name]
        for r in rects_in_table:
            cv.Rectangle(image2, (r[0], r[1]), (r[0] + r[2], r[1] + r[3]),
                         cv.CV_RGB(0, 255, 0), pen_width)

    # redraw new rect
    if has_roi:
        cv.Rectangle(image2, (roi_x0, roi_y0), (cur_mouse_x, cur_mouse_y),
                     cv.CV_RGB(255, 0, 255), pen_width)

    # draw background
    if current_img_file_name in background_files:
        cv.Line(image2, (0, 0), (image2.width, image2.height),
                cv.CV_RGB(255, 0, 0))
        cv.Line(image2, (0, image2.height), (image2.width, 0),
                cv.CV_RGB(255, 0, 0))

    cv.ShowImage(window_name, image2)
def find_leds(thresh_img):
    """
    Given a binary image showing the brightest pixels in an image, 
    returns a result image, displaying found leds in from PIL import Image
a rectangle
    """
    contours = cv2.FindContours(thresh_img,
                                cv2.CreateMemStorage(),
                                mode=cv2.CV_RETR_EXTERNAL,
                                method=cv2.CV_CHAIN_APPROX_NONE,
                                offset=(0, 0))

    regions = []
    while contours:
        pts = [pt for pt in contours]
        x, y = zip(*pts)
        min_x, min_y = min(x), min(y)
        width, height = max(x) - min_x + 1, max(y) - min_y + 1
        regions.append((min_x, min_y, width, height))
        contours = contours.h_next()

        out_img = cv2.CreateImage(cv2.GetSize(grey_img), 8, 3)
    for x, y, width, height in regions:
        pt1 = x, y
        pt2 = x + width, y + height
        color = (0, 0, 255, 0)
        cv2.Rectangle(out_img, pt1, pt2, color, 2)

    return out_img, regions
def DetectFace(image, faceCascade, returnImage=False):
    # This function takes a grey scale cv image and finds
    # the patterns defined in the haarcascade function
    # modified from: http://www.lucaamore.com/?p=638

    #variables
    min_size = (20, 20)
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Equalize the histogram
    cv2.EqualizeHist(image, image)

    # Detect the faces
    faces = cv2.HaarDetectObjects(image, faceCascade, cv2.CreateMemStorage(0),
                                  haar_scale, min_neighbors, haar_flags,
                                  min_size)

    # If faces are found
    if faces and returnImage:
        for ((x, y, w, h), n) in faces:
            # Convert bounding box to two CvPoints
            pt1 = (int(x), int(y))
            pt2 = (int(x + w), int(y + h))
            cv2.Rectangle(image, pt1, pt2, cv2.RGB(255, 0, 0), 5, 8, 0)

    if returnImage:
        return image
    else:
        return faces
예제 #5
0
def DetectEyes(imageCV, faceCascade, eyeCascade):
    minSize = (20, 20)
    imageScale = 2
    haarScale = 1.2
    minNeighbors = 2
    haarFlags = 0

    # Allocate the temporary images
    #gray = cv2.CreateImage((imageCV.width, image.height), 8, 1)
    #smallImage = cv.CreateImage((cv.Round(image.width / image_scale), cv2.Round (image.height / image_scale)), 8 ,1)

    # Convert color input image to grayscale
    cv2.cvtColor(image, gray, cv.CV_BGR2GRAY)

    # Scale input image for faster processing
    cv2.Resize(gray, smallImage, cv.CV_INTER_LINEAR)

    # Equalize the histogram
    cv2.EqualizeHist(smallImage, smallImage)

    # Detect the faces
    faces = cv2.HaarDetectObjects(smallImage, faceCascade,
                                  cv2.CreateMemStorage(0), haar_scale,
                                  min_neighbors, haar_flags, min_size)

    # If faces are found
    if faces:

        for ((x, y, w, h), n) in faces:
            # the input to cv.HaarDetectObjects was resized, so scale the
            # bounding box of each face and convert it to two CvPoints
            pt1 = (int(x * image_scale), int(y * image_scale))
            pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
            cv2.Rectangle(image, pt1, pt2, cv2.RGB(255, 0, 0), 3, 8, 0)
예제 #6
0
파일: qr2.py 프로젝트: pocorschi/qr_test
def scanner_procces(frame, set_zbar):
    set_width = 100.0 / 100
    set_height = 90.0 / 100

    coord_x = int(frame.width * (1 - set_width) / 2)
    coord_y = int(frame.height * (1 - set_height) / 2)
    width = int(frame.width * set_width)
    height = int(frame.height * set_height)

    get_sub = cv.GetSubRect(frame,
                            (coord_x + 1, coord_y + 1, width - 1, height - 1))

    cv.Rectangle(frame, (coord_x, coord_y),
                 (coord_x + width, coord_y + height), (255, 0, 0))

    cm_im = cv.CreateImage((get_sub.width, get_sub.height), cv.IPL_DEPTH_8U, 1)
    cv.ConvertImage(get_sub, cm_im)
    image = zbar.Image(cm_im.width, cm_im.height, 'Y800', cm_im.tostring())

    set_zbar.scan(image)
    for symbol in image:
        print '\033[1;32mResult : %s symbol "%s" \033[1;m' % (symbol.type,
                                                              symbol.data)

    cv.ShowImage("webcame", frame)
    #cv.ShowImage("webcame2", get_sub)
    cv.WaitKey(10)
예제 #7
0
def DetectFace(image, faceCascade, returnImage=False):
    min_size = (20, 20)
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Equalize the histogram
    cv.EqualizeHist(image, image)

    # Detect the faces
    faces = cv.HaarDetectObjects(image, faceCascade, cv.CreateMemStorage(0),
                                 haar_scale, min_neighbors, haar_flags,
                                 min_size)

    # If faces are found
    if faces and returnImage:
        for ((x, y, w, h), n) in faces:
            # Convert bounding box to two CvPoints
            pt1 = (int(x), int(y))
            pt2 = (int(x + w), int(y + h))
            cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)

    if returnImage:
        return image
    else:
        return faces
예제 #8
0
def show(area):
    cv2.Rectangle(img, (area[0][0], area[0][1]),
                  (area[0][0] + area[0][2], area[0][1] + area[0][3]),
                  (255, 0, 0), 2)
    cv2.NamedWindow('Face Detection', cv2.CV_WINDOW_NORMAL)
    cv2.imread('Face Detection', img)
    cv2.WaitKey()
예제 #9
0
def DetectFace(image, faceCascade):
    #modified from: http://www.lucaamore.com/?p=638

    min_size = (20, 20)
    image_scale = 1
    haar_scale = 1.1
    min_neighbors = 3
    haar_flags = 0

    # Allocate the temporary images
    smallImage = cv2.CreateImage((cv2.Round(
        image.width / image_scale), cv2.Round(image.height / image_scale)), 8,
                                 1)

    # Scale input image for faster processing
    cv2.Resize(image, smallImage, cv2.CV_INTER_LINEAR)

    # Equalize the histogram
    cv2.EqualizeHist(smallImage, smallImage)

    # Detect the faces
    faces = cv2.HaarDetectObjects(smallImage, faceCascade,
                                  cv2.CreateMemStorage(0), haar_scale,
                                  min_neighbors, haar_flags, min_size)

    # If faces are found
    if faces:
        for ((x, y, w, h), n) in faces:
            # the input to cv.HaarDetectObjects was resized, so scale the
            # bounding box of each face and convert it to two CvPoints
            pt1 = (int(x * image_scale), int(y * image_scale))
            pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
            cv2.Rectangle(image, pt1, pt2, cv2.RGB(255, 0, 0), 5, 8, 0)

    return image
예제 #10
0
 def __init__(self, iplimage):
     # Rough-n-ready but it works dammit
     alpha = cv.CreateMat(iplimage.height, iplimage.width, cv.CV_8UC1)
     cv.Rectangle(alpha, (0, 0), (iplimage.width, iplimage.height),
                  cv.ScalarAll(255), -1)
     rgba = cv.CreateMat(iplimage.height, iplimage.width, cv.CV_8UC4)
     cv.Set(rgba, (1, 2, 3, 4))
     cv.MixChannels(
         [iplimage, alpha],
         [rgba],
         [
             (0, 0),  # rgba[0] -> bgr[2]
             (1, 1),  # rgba[1] -> bgr[1]
             (2, 2),  # rgba[2] -> bgr[0]
             (3, 3)  # rgba[3] -> alpha[0]
         ])
     self.__imagedata = rgba.tostring()
     super(IplQImage, self).__init__(self.__imagedata, iplimage.width,
                                     iplimage.height, QImage.Format_RGB32)
예제 #11
0
    def detect_and_draw(self, img):

        # allocate temporary images
        gray = cv.CreateImage((img.width, img.height), 8, 1)
        small_img = cv.CreateImage((cv.Round(img.width / self.image_scale),
                                    cv.Round(img.height / self.image_scale)),
                                   8, 1)

        # convert color input image to grayscale
        cv.CvtColor(img, gray, cv.CV_BGR2GRAY)

        # scale input image for faster processing
        cv.Resize(gray, small_img, cv.CV_INTER_LINEAR)
        cv.EqualizeHist(small_img, small_img)

        if self.cascade:
            t = cv.GetTickCount()
            faces = cv.HaarDetectObjects(small_img, self.cascade,
                                         cv.CreateMemStorage(0),
                                         self.haar_scale, self.min_neighbors,
                                         self.haar_flags, self.min_size)
            t = cv.GetTickCount() - t
            #		print "time taken for detection = %gms" % (t/(cv.GetTickFrequency()*1000.))
            if faces:
                face_found = True

                for ((x, y, w, h), n) in faces:
                    # the input to cv.HaarDetectObjects was resized, so scale the
                    # bounding box of each face and convert it to two CvPoints
                    pt1 = (int(x * self.image_scale),
                           int(y * self.image_scale))
                    pt2 = (int((x + w) * self.image_scale),
                           int((y + h) * self.image_scale))
                    cv.Rectangle(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8, 0)
            else:
                face_found = False

        cv.ShowImage("video", img)
        return face_found
예제 #12
0
    def detectFace(self, cam_img, faceCascade, eyeCascade, mouthCascade):  # cam_img should be cv2.cv.iplcam_img
        min_size = (20, 20)
        image_scale = 2
        haar_scale = 1.2
        min_neighbors = 2
        haar_flags = 0
        image_width = int(cam_img.get(cv.CV_CAP_PROP_FRAME_WIDTH))
        image_height = int(cam_img.get(cv.CV_CAP_PROP_FRAME_HEIGHT))
        # Allocate the temporary images
        gray = cv.CreateImage((image_width, image_height), 8, 1)  # tuple as the first arg
        smallImage = cv.CreateImage((cv.Round(image_width / image_scale), cv.Round(image_height / image_scale)), 8, 1)

        (ok, img) = cam_img.read()
        # print 'gray is of ',type(gray) >>> gray is of  <type 'cv2.cv.iplimage'>
        # print type(smallImage)  >>> <type 'cv2.cv.iplimage'>
        # print type(image) >>> <type 'cv2.VideoCapture'>
        # print type(img) >>> <type 'numpy.ndarray'>

        # convert numpy.ndarray to iplimage
        ipl_img = cv2.cv.CreateImageHeader((img.shape[1], img.shape[0]), cv.IPL_DEPTH_8U, 3)
        cv2.cv.SetData(ipl_img, img.tostring(), img.dtype.itemsize * 3 * img.shape[1])

        # Convert color input image to grayscale
        cv.CvtColor(ipl_img, gray, cv.CV_BGR2GRAY)

        # Scale input image for faster processing
        cv.Resize(gray, smallImage, cv.CV_INTER_LINEAR)

        # Equalize the histogram
        cv.EqualizeHist(smallImage, smallImage)

        # Detect the faces
        faces = cv.HaarDetectObjects(smallImage, faceCascade, cv.CreateMemStorage(0),
                                     haar_scale, min_neighbors, haar_flags, min_size)
        # => The function returns a list of tuples, (rect, neighbors) , where rect is a CvRect specifying the object’s extents and neighbors is a number of neighbors.
        # => CvRect cvRect(int x, int y, int width, int height)
        # If faces are found
        if faces:
            face = faces[0]
            self.faceX = face[0][0]
            self.faceY = face[0][1]

            for ((x, y, w, h), n) in faces:
                # the input to cv.HaarDetectObjects was resized, so scale the
                # bounding box of each face and convert it to two CvPoints
                pt1 = (int(x * image_scale), int(y * image_scale))
                pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
                cv.Rectangle(ipl_img, pt1, pt2, cv.RGB(0, 0, 255), 3, 8, 0)
                # face_region = cv.GetSubRect(ipl_img,(x,int(y + (h/4)),w,int(h/2)))

            cv.SetImageROI(ipl_img, (pt1[0],
                                     pt1[1],
                                     pt2[0] - pt1[0],
                                     int((pt2[1] - pt1[1]) * 0.7)))

            eyes = cv.HaarDetectObjects(ipl_img, eyeCascade,
                                        cv.CreateMemStorage(0),
                                        haar_scale, min_neighbors,
                                        haar_flags, (15, 15))

            if eyes:
                # For each eye found
                for eye in eyes:
                    # Draw a rectangle around the eye
                    cv.Rectangle(ipl_img,  # image
                                 (eye[0][0],  # vertex pt1
                                  eye[0][1]),
                                 (eye[0][0] + eye[0][2],  # vertex pt2 opposite to pt1
                                  eye[0][1] + eye[0][3]),
                                 cv.RGB(255, 0, 0), 1, 4, 0)  # color,thickness,lineType(8,4,cv.CV_AA),shift

        cv.ResetImageROI(ipl_img)

        return ipl_img
예제 #13
0
def detect_and_draw(img, cascade):
    t = cv2.GetTickCount()  ## start counter
    cv2.CvtColor(img, gray, cv2.CV_BGR2GRAY)
    cv2.Resize(gray, small_img, cv2.CV_INTER_LINEAR)

    #Ages all trackedFaces
    for f in trackedFaces:
        f.updateLife()
    #Remove expired faces
    for f in trackedFaces:
        if (f.isTooOld()):
            trackedFaces.remove(f)

    faces = cv2.HaarDetectObjects(small_img, cascade, storage, haar_scale,
                                  min_neighbors, haar_flags, min_size)
    drawline = 0
    if faces:
        #found a face
        for ((x, y, w, h), n) in faces:
            matchedFace = False
            pt1 = (int(x * image_scale), int(y * image_scale))
            pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
            pt3 = (int(x * image_scale) + int(
                ((x + w) * image_scale - x * image_scale) / 3),
                   int(y * image_scale))
            pt4 = (int((x + w) * image_scale) - int(
                ((x + w) * image_scale - x * image_scale) / 3),
                   int((y * image_scale) + int((
                       (y + h) * image_scale) - int(y * image_scale)) / 3))

            #check if there are trackedFaces
            if (len(trackedFaces) > 0):
                #each face being tracked
                for f in trackedFaces:
                    #the face is found (small movement)
                    if ((abs(f.xpt - pt1[0]) < FACE_MAX_MOVEMENT)
                            and (abs(f.ypt - pt1[1]) < FACE_MAX_MOVEMENT)):
                        matchedFace = True
                        f.updateFace(int(w * image_scale),
                                     int(h * image_scale), pt1[0], pt1[1])
                        mf = f
                        break

                #if face not found, add a new face
                if (matchedFace == False):
                    f = Face(0, int(w * image_scale), int(h * image_scale),
                             pt1[0], pt1[1], 0)
                    trackedFaces.append(f)
                    mf = f
            #No tracked faces: adding one
            else:
                f = Face(0, int(w * image_scale), int(h * image_scale), pt1[0],
                         pt1[1], 0)
                trackedFaces.append(f)
                mf = f
            #where to draw face and properties
            if (mf.age > 5):

                #draw attention line
                lnpt1 = (int(mf.xpt * scale), int(mf.ypt * scale - 5) - 5)
                if (mf.age > mf.width):
                    lnpt2 = (int(mf.xpt * scale + mf.width),
                             int(mf.ypt * scale - 5))
                else:
                    lnpt2 = (int(mf.xpt * scale + mf.age),
                             int(mf.ypt * scale - 5))

                cv2.Rectangle(img, lnpt1, lnpt2, RED, 4, 8,
                              0)  ## drawing bolded attention line

                ### draw eyes
                cv2.Rectangle(img, mf.eyeLeft1, mf.eyeLeft2, MAGENTA, 3, 8, 0)
                cv2.Rectangle(img, mf.eyeRight1, mf.eyeRight2, MAGENTA, 3, 8,
                              0)
                #
                ### draw mouth
                cv2.Rectangle(img, mf.mouthTopLeft, mf.mouthBotRight, ORANGE,
                              3, 8, 0)
                #
                ### draw face
                cv2.Rectangle(img, pt1, pt2, getColor(mf), 3, 8, 0)
                #cv2.Rectangle( img, pt3, pt4, MAGENTA, 1, 8, 0 ) #forehead
                drawline = mf.age

    if (CAPTURING): saveAsJPG(img)
    if (osName == "nt"): cv2.Flip(img, img, 0)
    cv2.ShowImage('Camera', img)
    t = cv2.GetTickCount() - t  ## counter for FPS
    print("%i fps." % (cv2.GetTickFrequency() * 1000000. / t))  ## print FPS
예제 #14
0
                location = [i, j]

    return location


# load source and template images
source_img = cv2.imread('E:/EC601/source_img.jpg')  # read image in grayscale
temp = cv2.imread('E:/EC601/template.jpg')  # read image in grayscale
location = TemplateMatching(source_img, temp, 20)
print(location)
match_img = cv2.cvtColor(source_img, cv2.COLOR_BGR2GRAY)

# Draw a red rectangle on match_img to show the template matching result
# ------------------ Put your code below ------------------
location2 = [location(0) + temp.shape(0), location(0) + temp.shape(1)]
match_img = cv2.Rectangle(match_img, location, location2, (255, 0, 0), 3)
cv2.rectangle(match_img, (location[1], location[0]),
              (location[1] + temp.shape[1], location[0] + temp.shape[0]),
              (0, 0, 255), 5)

# Save the template matching result image (match_img)
# ------------------ Put your code below ------------------
cv2.imwrite('match_img.jpg', match_img)

# Display the template image and the matching result
cv2.namedWindow('TemplateImage', cv2.WINDOW_NORMAL)
cv2.namedWindow('MyTemplateMatching', cv2.WINDOW_NORMAL)
cv2.imshow('TemplateImage', temp)
cv2.imshow('MyTemplateMatching', match_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
예제 #15
0

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('chimpanzee.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:
    cv2.Rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for(ex,ey,ew,eh) in eyes:
        cv2.Rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

예제 #16
0
def showNaoImage(IP, PORT, camID):  # 参数分别为IP、PORT、摄像头ID(区分上下摄像头)

    #链接nao的摄像头
    camProxy = ALProxy("ALVideoDevice", IP, PORT)

    resolution = 2  # VGA``
    colorSpace = 11  # RGB
    videoClient = camProxy.subscribe("python_client", resolution, colorSpace,
                                     5)  # 设置分辨率、帧速、颜色空间

    t0 = time.time()
    camProxy.setParam(18, camID)  # 设置摄像头

    naoImage = camProxy.getImageRemote(videoClient)  #  将获取的图像赋给naoImage
    t1 = time.time()

    camProxy.unsubscribe(videoClient)
    imageWidth = naoImage[0]
    imageHeight = naoImage[1]
    imagechannls = naoImage[2]  # naoImage[6]为imagedata

    frameArray = numpy.frombuffer(naoImage[6], dtype=numpy.uint8).reshape(
        imageHeight, imageWidth, imagechannls)
    cimg = cv2.cvtColor(frameArray, cv2.COLOR_BGR2HSV)
    gray = cv2.cvtColor(frameArray, cv2.COLOR_BGR2GRAY)  # 转换为BGR图像
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)  # 霍夫降噪 平滑处理
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]  # 取得二值图
    # im_cv = numpy.zeros((imageHeight, imageWidth, 3), numpy.uint8)#初始化图像im_cv
    #
    # im_cv.data = array  #将从摄像头获取的图像copy到im_cv,转为mat
    #
    # # 转化颜色空间由BGR到RGB
    # b, g, r = cv2.split(im_cv)
    # img1 = cv2.merge([r, g, b])
    # # 转mat到cvmat
    # img3 = cv2.fromarray(img1)
    # cv2.SaveImage("test22.bmp",img3)
    # #转换颜色空间到HSV
    # imgHSV = cv2.CreateImage(cv2.GetSize(img3), 8, 3)
    # cv2.CvtColor(img3, imgHSV, cv2.CV_RGB2HSV)
    #
    # cimg,cimg_c=hsvProceed(imgHSV,camID) # 调用hsvProceed处理图像,返回二值图
    #圈取最小矩形框
    #初始化
    storage = cv2.CreateMemStorage(0)
    cnts = cv2.FindContours(thresh, storage, cv2.RETR_LIST,
                            cv2.CHAIN_APPROX_SIMPLE)
    currtnt = cnts
    Area = 0
    left_right = 0
    up_down = 0
    #为不同摄像头设置不同筛选条件
    if camID == 0:
        areamax = 2500
        areamin = 40
        valuemin = 25
        value_w = 641
        valuemax = 481
    else:
        areamax = 5000
        areamin = 400
        valuemin = 0
        value_w = 500
        valuemax = 400

    while cnts:
        rect = cv2.BoundingRect(cnts, 0)  #获得单连通矩形框
        area = rect[2] * rect[3]  #获得矩形框面积
        #获得矩形框中心点坐标
        rect_center_x = rect[0] + rect[2] / 2
        rect_center_y = rect[1] + rect[3] / 2
        #调用choose0文件下的radio函数,筛选圆形部分
        # radio_c = choose0.radio(cimg_c,rect)

        radio = float(rect[2]) / rect[3]  #计算矩形框的长宽比
        #以下if语句均为筛选条件
        if rect[1] >= valuemin:
            if rect[1] <= valuemax:
                if rect[0] <= value_w:
                    if area > areamin:
                        if area < areamax:
                            if radio > 0.6:
                                if radio < 1.6:
                                    # if radio_c == 1:
                                    cv2.DrawContours(frameArray, cnts,
                                                     (255, 255, 0),
                                                     (255, 255, 0), 0,
                                                     1)  #画出单连通轮廓
                                    cv2.Rectangle(
                                        frameArray, (rect[0], rect[1]),
                                        (rect[0] + rect[2], rect[1] + rect[3]),
                                        (0, 0, 255), 1)  #画出矩形框

                                    rect_center_x = rect[0] + rect[2] / 2
                                    rect_center_y = rect[1] + rect[3] / 2
                                    #计算通过条件的矩形框的面积以及在图像中的位置
                                    Area = rect[2] * rect[3]
                                    left_right = rect_center_x - cimg.width / 2
                                    up_down = rect_center_y - cimg.height / 2

        cnts = cnts.h_next()

    return Area, left_right, up_down  #返回球的面积以及在图像中的位置
#BuildingES.py
#!/usr/bin/python

import cv2  #import the openCV lib to python
import serial  #import the pyserial module

#Module -1: Image Processing
hc = cv2.imread(
    '/home/george/PycharmProjects/Embeded image processing system/haarcascade_frontalface_alt2.xml'
)
img = cv2.imshow('/home/jayneil/beautiful-faces.jpg', 0)
faces = cv2.HaarDetectObjects(img, hc, cv2.CreateMemStorage())
a = 1
print(faces)
for (x, y, w, h), n in faces:
    cv2.Rectangle(img, (x, y), (x + w, y + h), 255)
cv2.SaveImage("faces_detected.jpg", img)
dst = cv2.imread('faces_detected.jpg')
cv2.NamedWindow('Face Detected', cv2.CV_WINDOW_AUTOSIZE)
cv2.imshow('Face Detected', dst)
cv2.WaitKey(5000)
cv2.DestroyWindow('Face Detected')

#Module -2: Trigger Pyserial
if faces == []:

    ser = serial.Serial('/dev/ttyUSB0', 9600)
    print(ser)
    ser.write('N')
else:
        if draw_lineflag == 1:
            if draw_resetlineflag == 0:
                startb = new_minb
                startc = new_corro_c
                draw_resetlineflag = 1
            cv2.line(line_testimg, (startc, startb), (new_corro_c, new_minb),
                     (255, 0, 0), 5)
        cv2.circle(line_testimg, (new_corro_c, new_minb), 5,
                   (b_col, g_col, r_col), -1)
        cv2.imshow('line', line_testimg)
        cv2.waitKey(10)

    #######rectangledrawing
    elif shape_select == 4:

        line_testimg = cv2.addWeighted(yash, 0.5, yash, 0.5, 0)

        if draw_lineflag == 1:
            print "yash"
            sleep(2)
            if draw_resetlineflag == 0:
                startb = new_minb
                startc = new_corro_c
                draw_resetlineflag = 1
            cv2.Rectangle(line_testimg, (startc, startb),
                          (new_corro_c, new_minb), (255, 0, 0), -1)
        cv2.circle(line_testimg, (new_corro_c, new_minb), 5,
                   (b_col, g_col, r_col), -1)
        cv2.imshow('line', line_testimg)
        cv2.waitKey(10)
예제 #19
0
def draw_from_points(cv2_image, points):
    """Takes the cv2_image and points and draws a rectangle based on the points.
    Returns a cv2_image."""
    for (x, y, w, h), n in points:
        cv2.Rectangle(cv2_image, (x, y), (x + w, y + h), 255)
    return cv2_image
import cv2 as cv
import numpy as np
from utils import *
import sys 

'''
#For cv rectange documentation
cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0) → None¶
Parameters: 
img – Image.
pt1 – Vertex of the rectangle.
pt2 – Vertex of the rectangle opposite to pt1 .
rec – Alternative specification of the drawn rectangle.
color – Rectangle color or brightness (grayscale image).
thickness – Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a filled rectangle.
lineType – Type of the line. See the line() description.
shift – Number of fractional bits in the point coordinates.
'''

#Function for getting video feed via webcam
def getVideoFeed():
    cam = cv.VideoCapture(0); #0 enables the webcam device
    print ("Press Esc key to exit..");
    while True:
        x,img_frame = cam.read();
        if not x:
            print('Unable to read from camera feed');
            sys.exit(0);

        gray_scale_frame = cv.cvtColor(img_frame,cv.COLOR_BGR2GRAY);
        
    midFace = None

    if (cascade):
        # HaarDetectObjects takes 0.02s
        faces = cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
        if faces:
            lights(50 if len(faces) == 0 else 0, 50 if len(faces) > 0 else 0,
                   0, 50)

            for ((x, y, w, h), n) in faces:
                # the input to cv2.HaarDetectObjects was resized, so scale the
                # bounding box of each face and convert it to two CvPoints
                pt1 = (int(x * image_scale), int(y * image_scale))
                pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
                cv2.Rectangle(frame, pt1, pt2, cv2.RGB(100, 220, 255), 1, 8, 0)
                # get the xy corner co-ords, calc the midFace location
                x1 = pt1[0]
                x2 = pt2[0]
                y1 = pt1[1]
                y2 = pt2[1]

                midFaceX = x1 + ((x2 - x1) / 2)
                midFaceY = y1 + ((y2 - y1) / 2)
                midFace = (midFaceX, midFaceY)

                offsetX = midFaceX / float(frame.width / 2)
                offsetY = midFaceY / float(frame.height / 2)
                offsetX -= 1
                offsetY -= 1
예제 #22
0
    def draw_forehead(self, frame):
        x, y, w, h = self.forehead
        c = Annotator.COLOUR_FOREHEAD

        cv.Rectangle(frame, (int(x), int(y)), (int(x + w), int(y + h)), c,
                     Annotator.THIN)