Форум программистов, компьютерный форум, киберфорум
C++: OpenCV
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.96/55: Рейтинг темы: голосов - 55, средняя оценка - 4.96
70 / 14 / 4
Регистрация: 10.07.2018
Сообщений: 314

Интересные проекты на питон, кто может перевести на СИ?

19.08.2021, 11:29. Показов 11260. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ример 1
Проект: Распознавание жестов Автор: Gogul09 Файл: segment.py Лицензия: MIT License    11 голосов   проголосовать противголосовать за
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)
 
    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]
 
    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)
 
#-----------------
# MAIN FUNCTION
#-----------------

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Пример 2
Проект: Обнаружение объектов Автор: cristianpb Файл: motion.py Лицензия: MIT License  9 голосов    проголосовать противголосовать за
def prediction(self, image):
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        image = cv2.GaussianBlur(image, (21, 21), 0)
        if self.avg is None:
            self.avg = image.copy().astype(float)
        cv2.accumulateWeighted(image, self.avg, 0.5)
        frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg))
        thresh = cv2.threshold(
                frameDelta, DELTA_THRESH, 255,
                cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(
                thresh.copy(), cv2.RETR_EXTERNAL,
                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        self.avg = image.copy().astype(float)
        return cnts
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Пример 3
Проект: crop_row_detection Автор: petern3 Файл: camera_test.py Лицензия: GNU General Public License v3.0 8 голосов    проголосовать противголосовать за
def main():
    capture = cv2.VideoCapture(0)
    _, image = capture.read()
    previous = image.copy()
    
    
    while (cv2.waitKey(1) < 0):
        _, image = capture.read()
        diff = cv2.absdiff(image, previous)
        #image = cv2.flip(image, 3)
        #image = cv2.norm(image)
        _, diff = cv2.threshold(diff, 32, 0, cv2.THRESH_TOZERO)
        _, diff = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY)
        
        diff = cv2.medianBlur(diff, 5)
        
        cv2.imshow('video', diff)
        previous = image.copy()
        
    capture.release()
    cv2.destroyAllWindows()
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Пример 4
Проект: Peppa_Pig_Face_Engine Автор: 610265158 Файл: facer.py Лицензия: Apache Лицензия 2.0  7 голосов    проголосовать противголосовать за
def diff_frames(self,previous_frame,image):
        '''
        diff value for two value,
        determin if to excute the detection
 
        :param previous_frame:  RGB  array
        :param image:           RGB  array
        :return:                True or False
        '''
        if previous_frame is None:
            return True
        else:
 
            _diff = cv2.absdiff(previous_frame, image)
 
            diff=np.sum(_diff)/previous_frame.shape[0]/previous_frame.shape[1]/3.
 
            if diff>self.diff_thres:
                return True
            else:
                return False

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Пример 5
Проект: ATX Автор: NetEaseGame Файл: imutils.py Лицензия: Apache Лицензия 2.0    7 голосов    проголосовать противголосовать за
def diff_rect(img1, img2, pos=None):
    """find counters include pos in differences between img1 & img2 (cv2 images)"""
    diff = cv2.absdiff(img1, img2)
    diff = cv2.GaussianBlur(diff, (3, 3), 0)
    edges = cv2.Canny(diff, 100, 200)
    _, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    if not contours:
        return None
    contours.sort(key=lambda c: len(c))
    # no pos provide, just return the largest different area rect
    if pos is None:
        cnt = contours[-1]
        x0, y0, w, h = cv2.boundingRect(cnt)
        x1, y1 = x0+w, y0+h
        return (x0, y0, x1, y1)
    # else the rect should contain the pos
    x, y = pos
    for i in range(len(contours)):
        cnt = contours[-1-i]
        x0, y0, w, h = cv2.boundingRect(cnt)
        x1, y1 = x0+w, y0+h
        if x0 <= x <= x1 and y0 <= y <= y1:
            return (x0, y0, x1, y1)


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Пример 6
Проект: ATX Автор: NetEaseGame Файл: scene_detector.py Лицензия: Apache Лицензия 2.0 7 голосов    проголосовать противголосовать за
def get_match_confidence(img1, img2, mask=None):
    if img1.shape != img2.shape:
        return False
    ## first try, using absdiff
    # diff = cv2.absdiff(img1, img2)
    # h, w, d = diff.shape
    # total = h*w*d
    # num = (diff<20).sum()
    # print 'is_match', total, num
    # return num > total*0.90
    if mask is not None:
        img1 = img1.copy()
        img1[mask!=0] = 0
        img2 = img2.copy()
        img2[mask!=0] = 0
    ## using match
    match = cv2.matchTemplate(img1, img2, cv2.TM_CCOEFF_NORMED)
    _, confidence, _, _ = cv2.minMaxLoc(match)
    # print confidence
    return confidence
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Пример 7
Проект: Распознавание жестов Автор: Gogul09 Файл: recognize.py Лицензия: MIT License  6 голосов    проголосовать противголосовать за
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)
 
    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]
 
    # get the contours in the thresholded image
    (_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)
 
#--------------------------------------------------------------
# To count the number of fingers in the segmented hand region
#--------------------------------------------------------------

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Пример 8
Проект: Image-detect Автор: cangyan Файл: image_detect_02.py Лицензия: MIT License   6 голосов    проголосовать противголосовать за
def matchAB(fileA, fileB):
    # 读取图像数据
    imgA = cv2.imread(fileA)
    imgB = cv2.imread(fileB)
 
    # 转换成灰色
    grayA = cv2.cvtColor(imgA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imgB, cv2.COLOR_BGR2GRAY)
 
    # 获取图片A的大小
    height, width = grayA.shape
 
    # 取局部图像,寻找匹配位置
    result_window = np.zeros((height, width), dtype=imgA.dtype)
    for start_y in range(0, height-100, 10):
        for start_x in range(0, width-100, 10):
            window = grayA[start_y:start_y+100, start_x:start_x+100]
            match = cv2.matchTemplate(grayB, window, cv2.TM_CCOEFF_NORMED)
            _, _, _, max_loc = cv2.minMaxLoc(match)
            matched_window = grayB[max_loc[1]:max_loc[1]+100, max_loc[0]:max_loc[0]+100]
            result = cv2.absdiff(window, matched_window)
            result_window[start_y:start_y+100, start_x:start_x+100] = result
 
    plt.imshow(result_window)
    plt.show()

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Пример 9
Проект: Ручной жест-распознавание-использование-фон-эллиминация-и-свертка-нейронная сеть Автор: SparshaSaha Файл: ContinuousGesturePredictor.py Лицензия: MIT License 6 голосов    проголосовать противголосовать за
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)
 
    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff,
                                threshold,
                                255,
                                cv2.THRESH_BINARY)[1]
 
    # get the contours in the thresholded image
    (cnts, _) = cv2.findContours(thresholded.copy(),
                                    cv2.RETR_EXTERNAL,
                                    cv2.CHAIN_APPROX_SIMPLE)
 
    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Пример 10
Проект: Ручной жест-распознавание-использование-фон-эллиминация-и-свертка-нейронная сеть Автор: SparshaSaha Файл: PalmTracker.py Лицензия: MIT License    6 голосов    проголосовать противголосовать за
def segment(image, threshold=25):
    global bg
    # find the absolute difference between background and current frame
    diff = cv2.absdiff(bg.astype("uint8"), image)
 
    # threshold the diff image so that we get the foreground
    thresholded = cv2.threshold(diff,
                                threshold,
                                255,
                                cv2.THRESH_BINARY)[1]
 
    # get the contours in the thresholded image
    (cnts, _) = cv2.findContours(thresholded.copy(),
                                 cv2.RETR_EXTERNAL,
                                 cv2.CHAIN_APPROX_SIMPLE)
 
    # return None, if no contours detected
    if len(cnts) == 0:
        return
    else:
        # based on contour area, get the maximum contour which is the hand
        segmented = max(cnts, key=cv2.contourArea)
        return (thresholded, segmented)


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Пример 11
Проект: Обнаружение и отслеживание человека Автор: ITCoders Файл: main.py Лицензия: Apache License 2.0   6 голосов    проголосовать противголосовать за
def background_subtraction(previous_frame, frame_resized_grayscale, min_area):
    """
    This function returns 1 for the frames in which the area
    after subtraction with previous frame is greater than minimum area
    defined.
    Thus expensive computation of human detection face detection
    and face recognition is not done on all the frames.
    Only the frames undergoing significant amount of change (which is controlled min_area)
    are processed for detection and recognition.
    """
    frameDelta = cv2.absdiff(previous_frame, frame_resized_grayscale)
    thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.dilate(thresh, None, iterations=2)
    im2, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    temp = 0
    for c in cnts:
        # if the contour is too small, ignore it
        if cv2.contourArea(c) > min_area:
            temp = 1
    return temp


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Пример 12
Проект: ImageАнализ Автор: UASLab Файл: 1a-est-gyro-rates.py Лицензия: MIT Лицензия    6 голосов    проголосовать противголосовать за
def motion1(new_frame, base):
    motion = cv2.absdiff(base, new_frame)
    gray = cv2.cvtColor(motion, cv2.COLOR_BGR2GRAY)
    cv2.imshow('motion', gray)
    ret, motion_mask = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY_INV)
 
    blendsize = (3,3)
    kernel = np.ones(blendsize,'uint8')
    motion_mask = cv2.erode(motion_mask, kernel)
 
    # lots
    motion_mask /= 1.1429
    motion_mask += 16
 
    # medium
    #motion_mask /= 1.333
    #motion_mask += 32
 
    # minimal
    #motion_mask /= 2
    #motion_mask += 64
 
    cv2.imshow('motion1', motion_mask)
    return motion_mask


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Пример 13
Проект: ImageАнализ Автор: UASLab Файл: 1a-est-gyro-rates.py Лицензия: MIT Лицензия    6 голосов    проголосовать противголосовать за
def motion3(frame, counter):
    global last_frame
    global static_mask
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    if last_frame is None:
        pass
    else:
        diff = cv2.absdiff(gray, last_frame)
        cv2.imshow('motion3', diff)
        if static_mask is None:
            static_mask = np.float32(diff)
        else:
            if counter > 1000:
                c = float(1000)
            else:
                c = float(counter)
            f = float(c - 1) / c
            static_mask = f*static_mask + (1.0 - f)*np.float32(diff)
        mask_uint8 = np.uint8(static_mask)
        cv2.imshow('mask3', mask_uint8)
        ret, newmask = cv2.threshold(mask_uint8, 2, 255, cv2.THRESH_BINARY)
        cv2.imshow('newmask', newmask)
    last_frame = gray
 
# average of frames (the stationary stuff should be the sharpest)
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Пример 14
Проект: ImageАнализ Автор: UASLab Файл: 1a-est-gyro-rates.py Лицензия: MIT Лицензия    6 голосов    проголосовать противголосовать за
def motion1(new_frame, base):
    motion = cv2.absdiff(base, new_frame)
    gray = cv2.cvtColor(motion, cv2.COLOR_BGR2GRAY)
    cv2.imshow('motion', gray)
    ret, motion_mask = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY_INV)
 
    blendsize = (3,3)
    kernel = np.ones(blendsize,'uint8')
    motion_mask = cv2.erode(motion_mask, kernel)
 
    # lots
    motion_mask /= 1.1429
    motion_mask += 16
 
    # medium
    #motion_mask /= 1.333
    #motion_mask += 32
 
    # minimal
    #motion_mask /= 2
    #motion_mask += 64
 
    cv2.imshow('motion1', motion_mask)
    return motion_mask

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Пример 15
Проект: ImageАнализ Автор: UASLab Файл: 1b-est-gyro-rates.py Лицензия: MIT Лицензия    6 голосов    проголосовать противголосовать за
def motion1(new_frame, base):
    motion = cv2.absdiff(base, new_frame)
    gray = cv2.cvtColor(motion, cv2.COLOR_BGR2GRAY)
    cv2.imshow('motion', gray)
    ret, motion_mask = cv2.threshold(gray, 25, 255, cv2.THRESH_BINARY_INV)
 
    blendsize = (3,3)
    kernel = np.ones(blendsize,'uint8')
    motion_mask = cv2.erode(motion_mask, kernel)
 
    # lots
    motion_mask /= 1.1429
    motion_mask += 16
 
    # medium
    #motion_mask /= 1.333
    #motion_mask += 32
 
    # minimal
    #motion_mask /= 2
    #motion_mask += 64
 
    cv2.imshow('motion1', motion_mask)
    return motion_mask


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Пример 16
Проект: Цель Автор: aalto-ui Файл: pySaliencyMap.py Лицензия: MIT License    6 голосов    проголосовать противголосовать за
def FMCenterSurroundDiff(self, GaussianMaps):
        dst = list()
        for s in range(2, 5):
            now_size = GaussianMaps[s].shape
            now_size = (now_size[1], now_size[0]) # (width, height)
            tmp = cv2.resize(GaussianMaps[s + 3], now_size, interpolation=cv2.INTER_LINEAR)
            nowdst = cv2.absdiff(GaussianMaps[s], tmp)
            dst.append(nowdst)
            tmp = cv2.resize(GaussianMaps[s + 4], now_size, interpolation=cv2.INTER_LINEAR)
            nowdst = cv2.absdiff(GaussianMaps[s], tmp)
            dst.append(nowdst)
 
        return dst
 
 
    # Constructing a Gaussian pyramid + taking center-surround differences

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Пример 17
Проект: pynvr Автор: JFF-Bohdan Файл: motion_detection.py Лицензия: BSD 3-Clause "Новая" или "Пересмотренная" Лицензия 5 голосов    проголосовать противголосовать за
def motionDetected(self, new_frame):
        frame = self.preprocessInputFrame(new_frame)
 
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        gray = cv.GaussianBlur(gray, (21, 21), 0)
 
        if self.prevFrame is None:
            self.prevFrame = gray
            return False
 
        frameDiff = cv.absdiff(gray, self.prevFrame)
 
        # kernel = np.ones((5, 5), np.uint8)
 
        opening = cv.morphologyEx(frameDiff, cv.MORPH_OPEN, None)  # noqa
        closing = cv.morphologyEx(frameDiff, cv.MORPH_CLOSE, None)  # noqa
 
        ret1, th1 = cv.threshold(frameDiff, 10, 255, cv.THRESH_BINARY)
 
        height = np.size(th1, 0)
        width = np.size(th1, 1)
 
        nb = cv.countNonZero(th1)
 
        avg = (nb * 100) / (height * width)  # Calculate the average of black pixel in the image
 
        self.prevFrame = gray
 
        # cv.DrawContours(currentframe, self.currentcontours, (0, 0, 255), (0, 255, 0), 1, 2, cv.CV_FILLED)
        # cv.imshow("frame", current_frame)
 
        ret = avg > self.threshold   # If over the ceiling trigger the alarm
 
        if ret:
            self.updateMotionDetectionDts()
 
        return ret

Python
1
2
3
4
5
6
Пример 18
Проект: pynvr Автор: JFF-Bohdan Файл: motion_detection.py Лицензия: BSD 3-Clause "Новая" или "Пересмотренная" Лицензия 5 голосов    проголосовать противголосовать за
def diffImg(self, t0, t1, t2):
        d1 = cv.absdiff(t2, t1)
        d2 = cv.absdiff(t1, t0)
        return cv.bitwise_and(d1, d2)

Python
1
2
3
4
5
6
7
8
9
Пример 19
Проект: pynvr Автор: JFF-Bohdan Файл: motion_detection.py Лицензия: BSD 3-Clause "Новая" или "Пересмотренная" Лицензия 5 голосов    проголосовать противголосовать за
def diffImg(self, t0, t1, t2):
        if not self.multiFrameDetection:
            return cv.absdiff(t2, t1)
 
        d1 = cv.absdiff(t2, t1)
        d2 = cv.absdiff(t1, t2)
        return cv.bitwise_and(d1, d2)

Python
1
2
3
4
5
6
7
8
9
Пример 20
Проект: pynvr Автор: JFF-Bohdan Файл: motion_detection.py Лицензия: BSD 3-Clause "Новая" или "Пересмотренная" Лицензия 5 голосов    проголосовать противголосовать за
def diffImg(self, t0, t1, t2):
        if not self.multiFrameDetection:
            return cv.absdiff(t2, t1)
 
        d1 = cv.absdiff(t2, t1)
        d2 = cv.absdiff(t1, t2)
        return cv.bitwise_and(d1, d2)
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Пример 21
Проект: pi-timolo Автор: pageauc Файл: pi-timolo.py Лицензия: ЛИЦЕНЗИЯ MIT   5 голосов    проголосовать противголосовать за
def trackPoint(grayimage1, grayimage2):
    """
    Process two cropped grayscale images.
    check for motion and return center point
    of motion for largest contour.
    """
    movementCenterPoint = []  # initialize list of movementCenterPoints
    biggestArea = MIN_AREA
    # Get differences between the two greyed images
    differenceimage = cv2.absdiff(grayimage1, grayimage2)
    # Blur difference image to enhance motion vectors
    differenceimage = cv2.blur(differenceimage, (BLUR_SIZE, BLUR_SIZE))
    # Get threshold of blurred difference image
    # based on THRESHOLD_SENSITIVITY variable
    retval, thresholdimage = cv2.threshold(differenceimage,
                                           THRESHOLD_SENSITIVITY,
                                           255, cv2.THRESH_BINARY)
    try:
        # opencv2 syntax default
        contours, hierarchy = cv2.findContours(thresholdimage,
                                               cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_SIMPLE)
    except ValueError:
        # opencv 3 syntax
        thresholdimage, contours, hierarchy = cv2.findContours(thresholdimage,
                                                               cv2.RETR_EXTERNAL,
                                                               cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        for c in contours:
            cArea = cv2.contourArea(c)
            if cArea > biggestArea:
                biggestArea = cArea
                (x, y, w, h) = cv2.boundingRect(c)
                cx = int(x + w/2)   # x center point of contour
                cy = int(y + h/2)   # y center point of contour
                movementCenterPoint = [cx, cy]
    return movementCenterPoint
 
#------------------------------------------------------------------------------



Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Пример 22
Проект: pi-timolo Автор: pageauc Файл: pi-timolo81.py Лицензия: MIT Лицензия 5 голосов    проголосовать противголосовать за
def trackPoint(grayimage1, grayimage2):
    movementCenterPoint = []   # initialize list of movementCenterPoints
    biggestArea = MIN_AREA
    # Get differences between the two greyed images
    differenceimage = cv2.absdiff( grayimage1, grayimage2 )
    # Blur difference image to enhance motion vectors
    differenceimage = cv2.blur( differenceimage,(BLUR_SIZE,BLUR_SIZE ))
    # Get threshold of blurred difference image based on THRESHOLD_SENSITIVITY variable
    retval, thresholdimage = cv2.threshold( differenceimage, THRESHOLD_SENSITIVITY, 255, cv2.THRESH_BINARY )
    try:
        thresholdimage, contours, hierarchy = cv2.findContours( thresholdimage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
    except:
        contours, hierarchy = cv2.findContours( thresholdimage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
 
    if contours:
        movement = False
        for c in contours:
            cArea = cv2.contourArea(c)
            if cArea > biggestArea:
                biggestArea = cArea
                ( x, y, w, h ) = cv2.boundingRect(c)
                cx = int(x + w/2)   # x centerpoint of contour
                cy = int(y + h/2)   # y centerpoint of contour
                movementCenterPoint = [cx,cy]
    return movementCenterPoint
 
#-----------------------------------------------------------------------------------------------
Python
1
2
3
4
Пример 23
Проект: OpenCV-Python-Tutorial Автор: makelove Файл:图像相减 3.py Лицензия: MIT License  5 голосов    проголосовать противголосовать за
def diff(img, img1):  # returns just the difference of the two images
    return cv2.absdiff(img, img1)
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Пример 24
Проект: Грызун Автор: Keats Файл: rodent.py Лицензия: MIT Лицензия 5 голосов    проголосовать противголосовать за
def motion_detection(camera, folder, until):
    """
    Uses 3 frames to look for motion, can't remember where
    I found it but it gives better result than my first try
    with comparing 2 frames.
    """
    utils.clear_directory(folder)
 
    # Need to get 2 images to start with
    previous_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
    current_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
    purple = (140, 25, 71)
 
    while True:
        now = datetime.datetime.now()
        _, image = camera.read()
        gray_image = cv2.cvtColor(image, cv2.cv.CV_RGB2GRAY)
 
        difference1 = cv2.absdiff(previous_image, gray_image)
        difference2 = cv2.absdiff(current_image, gray_image)
        result = cv2.bitwise_and(difference1, difference2)
 
        # Basic threshold, turn the bitwise_and into a black or white (haha)
        # result, white (255) being a motion
        _, result = cv2.threshold(result, 40, 255, cv2.THRESH_BINARY)
 
        # Let's show a square around the detected motion in the original pic
        low_point, high_point = utils.find_motion_boundaries(result.tolist())
        if low_point is not None and high_point is not None:
            cv2.rectangle(image, low_point, high_point, purple, 3)
            print 'Motion detected ! Taking picture'
            utils.save_image(image, folder, now)
 
        previous_image = current_image
        current_image = gray_image
 
        if utils.time_over(until, now):
            break
 
    del(camera)
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
19.08.2021, 11:29
Ответы с готовыми решениями:

Интересные алгоритмы обработки сигналов, может кто не знал.
Начну с самого интересного из того, что недавно узнал. Это neutrosophic logic (нейтрософия). Замена обычной логики во многих алгоритмах....

Может кто-то может перевести на Делфи
Может есть кто-нибудь,кто может перевести на делфи.Очень нужно.:( http://suvitruf.ru/2012/05/16/1211/

Интересные проекты + исходники
Открыты исходники на некоторые мои проекты: http://emu-apparatchik.narod.ru/source.htm 1) IBM PC Pack Исходники для DOS/Win98....

1
70 / 14 / 4
Регистрация: 10.07.2018
Сообщений: 314
19.08.2021, 11:29  [ТС]
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Пример 25
Проект: pygta5 Автор: Sentdex Файл: motion.py Лицензия: GNU General Public License v3.0  5 голосов    проголосовать противголосовать за
def delta_images(t0, t1, t2):
    d1 = cv2.absdiff(t2, t0)
    return d1 
Пример 26
Проект: pygta5 Автор: Sentdex Файл: motion.py Лицензия: GNU General Public License v3.0  5 голосов    проголосовать противголосовать за
def delta_images(t0, t1, t2):
    d1 = cv2.absdiff(t2, t0)
    return d1 
Пример 27
Проект: pygta5 Автор: Sentdex Файл: main.py Лицензия: GNU General Public License v3.0    5 голосов    проголосовать противголосовать за
def delta_images(t0, t1, t2):
    d1 = cv2.absdiff(t2, t0)
    return d1 
Пример 28
Проект: pygta5 Автор: Sentdex Файл: motion.py Лицензия: GNU General Public License v3.0  5 голосов    проголосовать противголосовать за
def delta_images(t0, t1, t2):
    d1 = cv2.absdiff(t2, t0)
    return d1

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Пример 29
Проект: study-picamera-examples Автор: isaaxug Файл: motion_detector.py Лицензия: MIT License    5 голосов    проголосовать противголосовать за
def process_image(self, frame):
        frame = imutils.resize(frame, width=min(500, frame.shape[1]))
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)
 
        if self.avg is None:
            print('Starting background model...')
            self.avg = gray.copy().astype('float')
            return frame
 
        cv2.accumulateWeighted(gray, self.avg, 0.5)
        frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg))
        thresh = cv2.threshold(frameDelta, 5, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
 
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if imutils.is_cv2() else cnts[1]
 
        for c in cnts:
            if cv2.contourArea(c) < 5000:
                continue
 
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        return frame


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Пример 30
Проект: ActionAI Автор: smellslikeml Файл: demo.py Лицензия: GNU General Public License v3.0 5 голосов    проголосовать противголосовать за
def motion_detector(self, img):
        occupied = False
        # resize the frame, convert it to grayscale, and blur it
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (15, 15), 0)
     
        if self.avg is None:
            print("[INFO] starting background model...")
            self.avg = gray.copy().astype("float")
     
        # accumulate the weighted average between the current frame and
        # previous frames, then compute the difference between the current
        # frame and running average
        cv2.accumulateWeighted(gray, self.avg, 0.5)
        frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg))
        # threshold the delta image, dilate the thresholded image to fill
        # in holes, then find contours on thresholded image
        thresh = cv2.threshold(frameDelta, 5, 255,
            cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[1]
     
        # loop over the contours
        for c in cnts:
            # if the contour is too small, ignore it
            if cv2.contourArea(c) < 5000:
                pass
            occupied = True
     
        return occupied
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
19.08.2021, 11:29
Помогаю со студенческими работами здесь

Ищем Программиста C# на интересные проекты
Добрый день. Предлагаю Вам рассмотреть вакансию Программиста. В случае Вашей заинтересованности, прошу связаться со мной по телефону...

Кто может в VB перевести
Есть дву функции шифровка и дешифровка строки, помогите сделать аналогичную функцию дешифровки (DeCodeString) на visual basic или хотя бы...

Кто может перевести с Си# на Си++
using System; usingSystem.Collections.Generic; usingSystem.Runtime.Serialization; usingSystem.Runtime.Serialization.Json; using...

Кто может перевести с++ на с#?
Создала код на си++, в онлайн компиляторе работает программа, но в дев с++ не работает, нужно вводить значения самостоятельно почему-то и...

Кто может перевести?
Кто может помочь перевести? из Turbo Pascal в С uses crt; var s: string; i,k: byte; begin write('s='); readln(s); for...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Подключение Box2D v3 к SDL3 для Android: физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL3_image
8Observer8 27.01.2026
Содержание блога SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
Влияние грибов на сукцессию
anaschu 26.01.2026
Бифуркационные изменения массы гриба происходят тогда, когда мы уменьшаем массу компоста в 10 раз, а скорость прироста биомассы уменьшаем в три раза. Скорость прироста биомассы может уменьшаться за. . .
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru