zoukankan      html  css  js  c++  java
  • opencv 图像基本操作

    目录:读取图像,获取属性信息,图像ROI,图像通道的拆分和合并

    1.  读取图像

      像素值返回:直接使用坐标即可获得, 修改像素值:直接通过坐标进行赋值

      能用矩阵操作,便用,使用numpy中的array.item()以及array.itemset()会加快速度,逐渐修改像素会慢

    import cv2
    import numpy as np
    img = cv2.imread("test.jpg")
    #获取像素值
    px = img[100,100]
    blue = img[100,100,0]
    print(px, blue)
    #修改像素值
    img[100,100] = [255,255,255]
    print(img[100,100])
    #使用item
    print(img.item(10,10,2))
    img.itemset((10,10,2),100)
    print(img.item(10,10,2))

    2.  图像属性: 行、列、通道、数据类型、像素数目

    print(img.shape)
    #(342,548,3)   (342,548)  图像是灰度时,只有行和列
    print(img.size, img.dtype)
    #562248 uint8  图像像素数目, 图像数据类型,  注意:运行代码时数据类型是否一致

    3.  图像ROI

    ROI = img[y1:y2,x1:x2]

    4. 拆分以及合并图像通道

    b,g,r = cv2.split(img)
    img = cv2.merge(bgr)
    b = img[:,:,0]
    #修改时能尽量用numpy索引就用,用split比较耗时

    5.  图像加法及混合

    cv2.add(x, y)
    cv2.addWeighted(img1, 0.7, img2, 0.3, 0)   #dst = a* img1 + b*img2 + c

    6.  图像掩码

    import cv2
    import numpy as np
    # Load two images
    img1 = cv2.imread('messi5.jpg')
    img2 = cv2.imread('opencv-logo-white.png')
    
    # I want to put logo on top-left corner, So I create a ROI
    rows,cols,channels = img2.shape
    roi = img1[0:rows, 0:cols ]
    
    # Now create a mask of logo and create its inverse mask also
    img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
    ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
    mask_inv = cv2.bitwise_not(mask)
    
    # Now black-out the area of logo in ROI
    img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
    
    # Take only region of logo from logo image.
    img2_fg = cv2.bitwise_and(img2,img2,mask = mask)
    
    # Put logo in ROI and modify the main image
    dst = cv2.add(img1_bg,img2_fg)
    img1[0:rows, 0:cols ] = dst
    
    cv2.imshow('res',img1)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

      

     

  • 相关阅读:
    COCI2013-2014 Contest#3 F 单调栈
    Topcoder SRM568 Div1 DisjointSemicircles (二分图染色)
    COCI2013-2014 Contest#1 F SLASTIČAR
    TopCoder SRM 561 Orienteering(树形dp)
    COCI20122013 Contest#5 F
    2016 多校5 ATM
    2014多校6 Another Letter Tree
    HAOI2015 数组游戏
    [CCO 2017]接雨滴
    Luogu P6789 寒妖王
  • 原文地址:https://www.cnblogs.com/sword-/p/11344375.html
Copyright © 2011-2022 走看看