Python+OpenCV学习记录(三)

第3个OpenCV程序(三、获取像素取反,创建空的图像,计算运行时间)

代码经过测试,顺利执行!

一、Python版本与运行环境介绍

  • Python版本: 3.7.4
  • 操作系统: Win10
  • 运行环境: PyCharm 2019.3.5
  • OpenCV 4.4

二、Python代码实现

# -*- coding: utf-8 -*-
# @Time    : 2020/11/21 11:34
# @Author  : 11357
# @FileName: study_02.py
# @Software: PyCharm

# numpy 数组操作

import cv2 as cv
import numpy as np


def access_pixels(image):
    print(image.shape)
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    print("width : %s, height : %s channels : %s" % (width, height, channels))

    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row, col, c]
                # 取反
                image[row, col, c] = 255 - pv
    cv.imshow("pixel image", image)


# 创建空图像,并给图像一定的RGB值
def create_image():
    """
    # 3通道
    img = np.zeros([400, 400, 3], np.uint8)
#   img[:, :, 0] = np.ones([400, 400]) * 255  # blue green red
    img[:, :, 2] = np.ones([400, 400]) * 255  # blue green red
    cv.imshow("new image", img)
    """

    """
    # 单通道
    img = np.zeros([400, 400, 1], np.uint8)
    img[:, :, 0] = np.ones([400, 400]) * 127  # blue green red
    cv.imshow("new image", img)
    """

    # 创建一个都是1的矩阵并填充
    m1 = np.ones([3, 3], np.uint8)
    m1.fill(199)
    print(m1)

    # 修改矩阵的形状
    m2 = m1.reshape([1, 9])
    print(m2)

    np.array([2, 3, 4], [4, 5, 6], [7, 8, 9], np.uint32)


# 取反
def invert_img(image):
    dst = cv.bitwise_not(image)
    cv.imshow("inverse demo", dst)


print("------hello python------")
src = cv.imread("D:/VS OpenCV/images/001.png")
cv.namedWindow("test image", cv.WINDOW_AUTOSIZE)
cv.imshow("test image", src)
# 计算时间
t1 = cv.getTickCount()
# access_pixels(src)
invert_img(src)
# create_image()
t2 = cv.getTickCount()
time = (t2 - t1) / cv.getTickFrequency()
print("time : %s ms" % (time * 1000))
cv.waitKey(0)

print("hello python")

上一篇:CSV - 操作比较


下一篇:java url特殊字符报400