img_process

img_process.py 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cv2
import numpy as np


# 全局阈值
# notice the size of img
def threshold_demo(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 直接阈值化是对输入的单通道矩阵逐像素进行阈值分割。
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    print("threshold value %s" % ret)
    cv2.namedWindow("binary", cv2.WINDOW_NORMAL)
    cv2.imshow("binary", binary)


# 局部阈值
# notice the size of img
def local_threshold(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 自适应阈值化能够根据图像不同区域亮度分布,改变阈值
    binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
    cv2.imshow("local_threshold", binary)


# 用户自己计算阈值

def custom_threshold(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    h, w = gray.shape[:2]
    m = np.reshape(gray, [1, w * h])
    mean = m.sum() / (w * h)
    print("mean:", mean)
    ret, binary = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
    cv2.namedWindow("custom_threshold", cv2.WINDOW_NORMAL)
    cv2.imshow("custom_threshold", binary)



def big_img_binary(img):
    # 定义分割块的大小
    cw = 256
    ch = 256
    h, w = img.shape[:2]
    # 将图片转化为灰度图片
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    for row in range(0, h, ch):
        for col in range(0, w, cw):
            roi = gray[row:row + ch, col:col + cw]
            dst = cv2.adaptiveThreshold(roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 127, 20)
            gray[row:row + ch, col:col + cw] = dst
    cv2.imwrite('Binaryzation.png', gray)



#轮廓面积计算函数(所有)
def areaCal(contour):
    area = 0
    for i in range(len(contour)):
        area += cv2.contourArea(contour[i])
    return area


def test():
    src = cv2.imread('/home/pi/project-car/foo.jpg')
    h, w, depth = src.shape
    # notice the resolution, if the pic is so large, the system will reboot
    img = cv2.resize(src, (int(w / 10), int(h / 10)), interpolation=cv.INTER_AREA)
    cv2.namedWindow('input_image', cv2.WINDOW_NORMAL)  # 设置为WINDOW_NORMAL可以任意缩放
    cv2.imshow('input_image', img)
    threshold_demo(img)
    local_threshold(img)
    custom_threshold(img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


src = cv2.imread('DEMO.jpg')
# threshold(src)
# local_threshold(src)
# custom_threshold(src)
# big_img_binary(src)
cv2.waitKey(0)
cv2.destroyAllWindows()

split_flow.py

import numpy as np
import os

root_path = "/youedata/linzhikun/code/data/Kinetics/val"


def splitflow(root_dirs):
    video_dirs = os.listdir(root_dirs)
    for video_dir in video_dirs:
        tmp = video_dir
        video_dir = os.path.join(root_dirs, video_dir)
        video_list = os.listdir(video_dir)
        for video in video_list:
            print(os.path.join(video_dir, video))
            image_list = os.listdir(os.path.join(video_dir, video))
            i_dir = os.path.join(video_dir, video, 'i')
            x_dir = os.path.join(video_dir, video, 'x')
            y_dir = os.path.join(video_dir, video, 'y')
            if not os.path.exists(i_dir):
                os.makedirs(i_dir)
            if not os.path.exists(x_dir):
                os.makedirs(x_dir)
            if not os.path.exists(y_dir):
                os.makedirs(y_dir)
            for image in image_list:
                classic = image.split('_')[0]
                cmd = 'mv %s %s'% (os.path.join(video_dir, video, image), os.path.join(video_dir, video, classic))
                if len(image.split('_')) > 1:
                    os.system(cmd)


if __name__ == '__main__':
    splitflow(root_path)

Python多进程opencv调用rtsp视频流(改进版)

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   test_cv.py    
@Contact :   476423448@qq.com
@License :   (C)Copyright 2020-2021, AIgroup-KPCQ

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
8/16/21 3:11 PM   gavin      1.0         None
'''

# import os
 
import gc
import abc
from multiprocessing import Process, Manager

import cv2


# 定义抽象基类,此类不能直接实例化
# 做好框架
# 其子类只用实现.process_image方法,返回任意图像算法处理后的从缓存栈中读取的图片
class ABVideoCapture(abc.ABC):
    def __init__(self, cam, top=100):
        self.stack = Manager().list()
        self.max_cache = top
        self.write_process = Process(target=self.__class__.write, args=(self.stack, cam, top))
        self.write_process.start()
        self.__read_gen = self.read_gen()

    @abc.abstractmethod
    def process_image(self, image):
        """
        对输入的图片进行处理并返回处理后的图片
        """

    def read_gen(self):
        while True:
            if len(self.stack) != 0:
                img = self.process_image(self.stack.pop())
                yield img

    def read(self):
        try:
            return True, next(self.__read_gen)
        except StopIteration:
            return False, None
        except TypeError:
            raise TypeError('{}.read_gen必须为生成器函数'.format(self.__class__.__name__))

    def __iter__(self):
        yield from self.__read_gen

    def release(self):
        self.write_process.terminate()

    def __del__(self):
        self.release()

    @staticmethod
    def write(stack, cam, top):
        """向共享缓冲栈中写入数据"""
        cap = cv2.VideoCapture(cam)
        while True:
            _, img = cap.read()
            if _:
                stack.append(img)
                # 每到一定容量清空一次缓冲栈
                # 利用gc库,手动清理内存垃圾,防止内存溢出
                if len(stack) >= top:
                    del stack[:]
                    gc.collect()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.release()


# 继承ABVideoCapture,对缓存栈中的图片不做处理直接返回
class VideoCapture(ABVideoCapture):
    def process_image(self, image):
        # 这里对图像的处理算法可以随意制定
        return image


if __name__ == '__main__':
    rtsp = 'rtsp://admin:kp123456@192.168.0.108:554/'
    camera_addr = rtsp

    cap = VideoCapture(camera_addr)
    while True:
        _, img = cap.read()
        if _:
            cv2.imshow('img', img)
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break

    cap.release()
    cv2.destroyAllWindows()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值