python opencv:像素操作

图片的像素

  • 像素:组成图片的单位
  • RGB:颜色由 RGB三种颜色组成
  • 颜色深度:对于8bit的颜色深度来说,它可以表示的颜色范围是 0 ~ 255,对于RGB图片来说,8位颜色深度可以表示 (2^8)^3 种颜色
  • 宽高:图片横向与纵向的像素点个数
  • 大小:宽 * 高 * 3 * 8 bit = xxx bit
  • alpha:有些图片还会有一个alpha通道,描绘图片的透明度信息

常见颜色存储格式:RGB、BGR

像素操作

获取一个具体点的像素值: r, g, b = img[x, y]

写入一个颜色到指定点:img[100,100]=[255,255,255]

使用NumPy的方法进行读取和写入

print( img.item(10,10,2))

img.itemset((10,10,2), 100)

Numpy 是经过优化了的进行快速矩阵运算的软件包。所以我们不推荐
逐个获取像素值并修改,这样会很慢,能有矩阵运算就不要用循环。

上面提到的方法被用来选取矩阵的一个区域,比如说前 5 行的后 3
列。对于获取每一个像素值,也许使用 Numpy 的 array.item() 和 array.itemset() 会更好。但是返回值是标量。如果你想获得所有 B, G, R 的
值,你需要使用 array.item() 分割他们。

像素取反

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  # 修改
    cv2.imshow("pixels_demo", image) 

使用 OpenCV 自带的API:

dst = cv2.bitwise_not(image)

这个操作底层是用C++操作的,比起自己使用循环来操作速度快很多

NumPy 创建一张图片

def create_image():
    img = np.zeros([400, 400, 3], np.uint8)
    # img = np.zeros([400, 400, 1], np.uint8)  # 单通道图片
    # img[:, :, 0] = np.ones([400, 400])*127  # 单通道设置灰度图
    img[:, :, 0] = np.ones([400, 400])*255
    # img[:, :, 1] = np.ones([400, 400])*255
    # img[:, :, 2] = np.ones([400, 400])*255
    cv2.imshow("new image", img)
    # cv2.imwrite("images/demo.img")

猜你喜欢

转载自www.cnblogs.com/wbyixx/p/12217458.html