def write_video_file():
    path = file_utils.get_data_path(video1_name, "video")
    cap = cv2.VideoCapture(path)
    #创建一个VideoWrite的对象,确定输出文件名,指定FourCC编码,播放频率和帧的大小,最后是isColor标签True为彩色。
    #FourCC是一个4字节码,用来确定视频的编码格式。DIVX , XVID , MJPG , X264 , WMV1 , WMV2
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    #获取原视频的高和宽
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    #写入的视频的高和宽必须和原视频的高和宽一样,否则会打不开
    out = cv2.VideoWriter(file_utils.get_data_path(video1_1_name, "video"),
                          fourcc, 20.0, (width, height))
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            #图像翻转:1	水平翻转,0	垂直翻转, -1	水平垂直翻转
            frame = cv2.flip(frame, 0)
            #写入图片
            out.write(frame)
            cv2.imshow("image", frame)
            if cv2.waitKey(1) == ord("q"):
                break
        else:
            print("video write end...")
            break
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    file_utils.re_path_content(video1_1_name, "video")
예제 #2
0
def bitwise_operation():
    path1 = file_utils.get_data_path(constant.naruto_image, "image")
    path2 = file_utils.get_data_path(constant.spiralpill_image, "image")

    img1 = cv2.imread(path1)
    img2 = cv2.imread(path2)
    # 我想在左上角放置徽标,所以我创建了一个ROI
    rows, cols, channels = img2.shape
    roi = img1[0:rows, 0:cols]
    # 现在创建一个徽标掩码并创建其反转掩码
    img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    #ret, dst = cv2.threshold(src, thresh, maxval, type),参数分别是:输入图、阈值、当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值、二值化操作的类型
    #设置图像阈值,如下:大于175的设为255, 小于175的设为0
    ret, mask = cv2.threshold(img2gray, 175, 255, cv2.THRESH_BINARY)
    #将二指图片的效果反转既黑色变白色,白色变黑色。
    mask_inv = cv2.bitwise_not(mask)
    # 现在,ROI中的徽标区域变黑
    # 取ROI中与mask中不为零的值对应的像素的值,其让值为0 。
    # 注意这里必须有mask=mask或者mask=mask_inv,其中mask=不能忽略
    img1_bg = cv2.bitwise_and(roi, roi, mask=mask)
    # 取roi中与mask_inv中不为零的值对应的像素的值,其他值为0
    # 仅从徽标图像中获取徽标区域。
    img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)

    # 在ROI中放置徽标并修改主图像
    dst = cv2.add(img1_bg, img2_fg)
    img1[0:rows, 0:cols] = dst

    cv2.imshow('res', img1)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
예제 #3
0
def cv2_waitkey_func_test():
    img_path = file_utils.get_data_path(naruto_image, "image")
    img = cv2.imread(img_path, cv2.IMREAD_COLOR)
    cv2.imshow("image", img)
    k = cv2.waitKey()
    if k == 27:
        cv2.destroyWindow("image")
    elif k == ord('s'):
        cv2.imwrite(file_utils.get_data_path("cv2_test.jpg", "image"), img)
        file_utils.re_path_content("cv2_test.jpg", "image")
        cv2.destroyWindow("image")
예제 #4
0
def image_pyramid():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    image_dowm = cv2.pyrDown(img)
    image_up = cv2.pyrUp(img)

    #3个维度不同
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    image_dowm = cv2.cvtColor(image_dowm, cv2.COLOR_BGR2RGB)
    image_up = cv2.cvtColor(image_up, cv2.COLOR_BGR2RGB)

    plt.subplot(1, 3, 1)
    plt.imshow(img)
    plt.title("img")
    plt.xticks([])
    plt.yticks([])
    plt.subplot(1, 3, 2)
    plt.imshow(image_dowm)
    plt.title("image_dowm")
    plt.xticks([])
    plt.yticks([])
    plt.subplot(1, 3, 3)
    plt.imshow(image_up)
    plt.title("image_up")
    plt.xticks([])
    plt.yticks([])
    plt.show()
예제 #5
0
def canny_edge():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    edges = cv2.Canny(img, 100, 200)

    plt.subplot(1, 2, 1); plt.imshow(img); plt.title("img"); plt.xticks([]); plt.yticks([])
    plt.subplot(1, 2, 2); plt.imshow(edges); plt.title("edges"); plt.xticks([]); plt.yticks([])
    plt.show()
예제 #6
0
def cv2_read_write_image():
    img_path = file_utils.get_data_path(naruto_image, "image")
    #cv2.IMREAD_COLOR读入彩色图像 cv2.IMREAD_GRAYSCALE以灰度模式读入图像
    img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
    cv2.namedWindow("image", cv2.WINDOW_NORMAL)
    cv2.imshow("image", img)
    cv2.waitKey(0)
    cv2.destroyWindow("image")
def mouse_test_case():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    cv2.namedWindow("image", cv2.WINDOW_NORMAL)
    cv2.setMouseCallback("image", mouse_event)
    while True:
        cv2.imshow("image", img)
        if cv2.waitKey(1) == ord("s"):
            break
    cv2.destroyWindow("image")
def check_program_effectiveness():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    e1 = cv2.getTickCount()
    for i in range(5, 49, 2):
        #中值滤波
        img = cv2.medianBlur(img, i)
    e2 = cv2.getTickCount()
    #转换单位为秒
    time = (e2 - e1) / cv2.getTickFrequency()
    print(time)
예제 #9
0
def image_mix():
    path1 = file_utils.get_data_path(constant.naruto_image, "image")
    path2 = file_utils.get_data_path(constant.sasuke_image, "image")

    img1 = cv2.imread(path1)
    img2 = cv2.imread(path2)
    #裁剪img1和img2图像的大小
    img1 = img1[0:1021]
    img2 = img2[:, 0:681]
    #img1的shape必须等于img2的shape
    img3 = cv2.addWeighted(img1, 0.3, img2, 0.7, 0)
    dict_image = {
        "naruto_image": img1,
        "sasuke_image": img2,
        "add_image": img3
    }
    cv2.namedWindow("image", cv2.WINDOW_NORMAL)
    for k, v in dict_image.items():
        cv2.setWindowTitle("image", k)
        cv2.imshow("image", v)
        cv2.waitKey()
    cv2.destroyAllWindows()
def profile():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray, 127, 255, 0)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_NONE)
    imag = cv2.drawContours(img, contours, 3, (0, 255, 0), 3)
    cv2.imshow('img', img)
    cv2.imshow('imgray', imgray)
    cv2.imshow('imag', imag)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
예제 #11
0
def print_all_color():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    cv2.namedWindow("image")
    colors = [x for x in dir(cv2) if x.startswith("COLOR_")]
    print(len(colors))
    dicts = {
        "COLOR_BGR2GRAY": cv2.COLOR_BGR2GRAY,
        "COLOR_BGR2HSV": cv2.COLOR_BGR2HSV
    }
    for k, y in dicts.items():
        cv2.setWindowTitle("image", k)
        img1 = cv2.cvtColor(img, y)
        cv2.imshow("image", img1)
        cv2.waitKey()
    cv2.destroyAllWindows()
예제 #12
0
def gradient_test():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    laplacian = cv2.Laplacian(img, cv2.CV_64F)
    sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
    sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)
    dicts = {"img": img, "laplacian": laplacian, "sobelx": sobelx, "sobely": sobely}
    index = 0
    for x, y in dicts.items():
        index += 1
        plt.subplot(2, 2, index)
        if x == "img":
            y = cv2.cvtColor(y, cv2.COLOR_BGR2RGB)
        plt.imshow(y)
        plt.title(x)
        plt.xticks([])
        plt.yticks([])
    plt.show()
def get_video_path():
    path = file_utils.get_data_path(video1_name, "video")
    cap = cv2.VideoCapture(path)
    if not cap.isOpened():
        #打开视频
        cap.open(video1_name)
        print("please open video.")
        return
    while True:
        ret, frame = cap.read()
        if not ret:
            print("video read end...")
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow("image", gray)
        if cv2.waitKey(100) & 0xFF == ord('q'):  # 按q键退出
            break
    cap.release()
    cv2.destroyAllWindows()
예제 #14
0
def object_tracking():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    # 转换到HSV
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # 设定蓝色的阀值
    lower_blue = np.array([110, 50, 50])
    upper_blue = np.array([130, 255, 255])
    # 根据阀值构建掩模->把lower_red~upper_red的范围值变为225,其他范围变为0吧
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    # 对原图和掩模进行位运算
    res = cv2.bitwise_and(img, img, mask=mask)
    # 显示图像
    cv2.imshow('img', img)
    cv2.imshow('hsv', hsv)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)
    cv2.waitKey()
    # 关闭窗口
    cv2.destroyAllWindows()
예제 #15
0
def morphology_test():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    kernel = np.ones((5, 5), np.uint8)
    #腐蚀:第一个是原始图像,第二个被称为结构化元素或者核,
    ersion = cv2.erode(img, kernel, iterations=1)
    #膨胀:与腐蚀相反,与卷积核对应的原图像的像素值中只要有一个是1,中心元素的像素值就是1
    dilation = cv2.dilate(img, kernel, iterations=1)
    #开运算:先进行腐蚀再进行膨胀就叫做开运算。被用来去除噪音,函数可以使用cv2.morphologyEx()
    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
    #闭运算:先膨胀再腐蚀。被用来填充前景物体中的小洞,或者前景上的小黑点。
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    #形态学梯度:其实就是一幅图像膨胀与腐蚀的差别。结果看上去就像前景物体的轮廓。
    gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
    #礼帽:原始图像与进行开运算之后得到的图像的差。
    tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
    #黑帽:进行闭运算之后得到的图像与原始图像的差。
    blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)

    dicts = {
        "img": img,
        "ersion": ersion,
        "dilation": dilation,
        "opening": opening,
        "closing": closing,
        "gradient": gradient,
        "tophat": tophat,
        "blackhat": blackhat
    }
    index = 0
    for x, y in dicts.items():
        index += 1
        plt.subplot(2, 4, index)
        y = cv2.cvtColor(y, cv2.COLOR_BGR2RGB)
        plt.imshow(y)
        plt.title(x)
        plt.xticks([])
        plt.yticks([])
    plt.show()
def contour_feature():
    path = file_utils.get_data_path(constant.naruto_image, "image")
    img = cv2.imread(path)
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray, 127, 255, 0)
    contours, hierarchy = cv2.findContours(thresh, 1, 2)
    cnt = contours[0]
    #1.图像的矩可以帮助我们计算图像的质心,面积等。函数cv2.moments()会将计算得到的矩以一个字典的形式返回。
    M = cv2.moments(cnt)
    #2.轮廓面积:可以使用函数cv2.contourArea()计算得到,也可以用矩(0阶矩),M['m00']。
    area = cv2.contourArea(cnt)
    #3.轮廓周长:也被称为弧长。可以使用函数cv2.arcLength()计算得到。这个函数的第二参数可以用来指定对象的形状是闭合的(True),还是打开的(一条曲线)。
    perimeter = cv2.arcLength(cnt, True)
    #4.轮廓近似:假设我们要在一幅图像中查找一个矩形,但是由于图像的种种原因我们不能得到一个完美的矩形,而是一个“坏形状”,现在就可以使用这个函数来近似这个形状,
    # 第二个参数是epsilon,它是从原始轮廓到近似轮廓的最大距离,它是一个准确度参数。
    epsilon = 0.1 * perimeter
    approx = cv2.approxPolyDP(cnt, epsilon, True)
    #5.凸包:函数cv2.convexHull()可以用来检测一个曲线是否具有凸性缺陷,并能纠正缺陷。
    hull = cv2.convexHull(cnt)
    #6.凸性检测:函数cv2.isContourConvex()可以检测一个曲线是不是凸的。它只能返回True或者False。
    k = cv2.isContourConvex(cnt)
    #7.边界矩形:直边界矩形,一个直矩形,没有旋转。不会考虑对象是否旋转
    x, y, w, h = cv2.boundingRect(cnt)
    img2 = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    #8.最小外接圆:函数cv2.minEnclosingCircle(),可以帮我们找到一个对象的外接圆。它是所有能够包括对象的圆中面积最小的一个。
    (x, y), radius = cv2.minEnclosingCircle(cnt)
    center = (int(x), int(y))
    radius = int(radius)
    img3 = cv2.circle(img, center, radius, (0, 255, 0), 2)
    #9.椭圆拟合:使用函数cv2.ellipse(),返回值其实就是旋转边界矩形的内切圆。
    ellipse = cv2.fitEllipse(cnt)
    img4 = cv2.ellipse(img, ellipse, (0, 255, 0), 2)
    #10.直线拟合:可以根据一组点拟合出一条直线,同样我们也可以为图像中的白色点拟合出一条直线。
    rows, cols = img.shape[:2]
    [vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
    lefty = int((x * vy / vx) + y)
    righty = int(((cols - x) * vy / vx) + y)
    img5 = cv2.line(img, (cols - 1, righty), (0, lefty), (0, 255, 0), 2)
    contents = {
        "图像的矩": M,
        "轮廓面积": area,
        "轮廓周长": perimeter,
        "轮廓近似": approx,
        "凸包": hull,
        "凸性检测": k
    }
    images = {
        "image": img,
        "rectangle": img2,
        "circle": img3,
        "ellipse": img4,
        "line": img5
    }
    for k, v in contents.items():
        print(k + "===>", v)
    index = 0
    for k, v in images.items():
        index += 1
        v_img = cv2.cvtColor(v, cv2.COLOR_BGR2RGB)
        plt.subplot(2, 3, index)
        plt.imshow(v_img)
        plt.title(k)
        plt.xticks([])
        plt.yticks([])
    plt.show()
예제 #17
0
import cv2
from util import file_utils, constant
from matplotlib import pyplot as plt

path = file_utils.get_data_path(constant.naruto_image, "image")


#当像素值高于阀值时,我们给这个像素赋予一个新值(可能是白色),否则我们给它赋予另外一种颜色(也许是黑色)
#cv2.threshold():第一个参数是原图像,原图像应该是灰度图、第二个参数就是用来对像素值进行分类的阀值,第三个参数就是当像素值高于(或者小于)阀值时,应该被赋予新的像素值。
#不同的阈值方法:cv2.THRESH_BINARY、cv2.THRESH_BINARY_INV、cv2.THRESH_TRUNC、cv2.THRESH_TOZERO、cv2.THRESH_TOZERO_INV
def basis_threshold():
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    res, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
    ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
    ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
    titles_imgs = {
        'original image': img,
        'Binary': thresh1,
        'binary-inv': thresh2,
        'trunc': thresh3,
        'tozero': thresh4,
        'tozero-inv': thresh5
    }
    index = 0
    for k, v in titles_imgs.items():
        index += 1
        plt.subplot(2, 3, index), plt.imshow(v, 'gray'), plt.title(k)
        #去掉x,y轴坐标
        plt.xticks([]), plt.yticks([])
def get_vedio_param():
    path = file_utils.get_data_path(video1_name, "video")
    cap = cv2.VideoCapture(path)
    for k, v in vedio_param.items():
        print(v, "param is==>", cap.get(k))