Basic operation image opencv

Contents: read image, acquiring the attribute information, the ROI image, image splitting and merging channels

1. The read image

  Returns a pixel value: can be obtained directly using the coordinate, modify the pixel values ​​of: directly by the coordinate assignment

  Use matrix operations, they use, use numpy in array.item () and array.itemset () will speed up, slow gradually will modify pixel

CV2 Import 
Import numpy AS NP 
IMG = cv2.imread ( "test.jpg") 
# Get the pixel value 
PX = img [100,100] 
Blue IMG = [100,100,0] 
Print (PX, Blue) 
# pixel values of the 
img [100,100] = [255,255,255] 
Print (IMG [100,100]) 
# use Item 
Print (img.item (10,10,2)) 
img.itemset ((10,10,2), 100) 
Print (img.item (10,10 ,2))

2. The image attributes: rows, columns, channels, data types, the number of pixels

Print (img.shape) 
# (342,548,3) (342,548) is a grayscale image, only the row and column 
Print (img.size, img.dtype) 
# 562 248 uint8 image pixel number, image data type, Note: Run Code when the data types are consistent

3. The image ROI

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

4. splitting and combining image channels

B, G, R & lt cv2.split = (IMG) 
IMG = cv2.merge (BGR) 
B = IMG [:,:, 0] 
# much as possible to use when modifying with numpy index, with split time-consuming

The image addition and mixing

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

6. The image mask

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()

  

 

Guess you like

Origin www.cnblogs.com/sword-/p/11344375.html