加载图片
import cv2
import matplotlib. pyplot as plt
image= cv2. imread( '~.jpg' )
width= image. shape[ 1 ]
height= image. shape[ 0 ]
channels= image. shape[ 2 ]
image= cv2. cvtColor( image, cv2. COLOR_BGR2RGB)
plt. imshow( image)
保存图片
cv. imwrite( "save_name" , image)
切片
image= cv2. imread( '~.jpg' ) = cv2. imread( '' )
image= cv2. cvtColor( image, cv2. COLOR_BGR2RGB)
( h, w, c) = image. shape
tl= image[ 0 : h// 2 , 0 : w// 2 ]
平移
def imread ( image_path) :
image= cv2. imread( image_path)
image= cv2. cvtColor( image, cv2. COLOR_RGB2BGR)
return image
def show ( image) :
plt. imshow( image)
plt. axis( 'off' )
plt. show( )
image= imread( 'image.jpg' )
M= np. float32( [ [ 1 , 0 , 250 ] , [ 0 , 1 , 500 ] ] )
shifted= cv2. warpAffine( image, M, ( image. shape[ 1 ] , image. shape[ 0 ] ) )
show( image)
show( shifted)
翻转
image= imread( 'image.jpg' )
flip= cv2. flip( image, 0 )
show( flip)
旋转
( h, w) = image. shape[ : 2 ]
M= cv2. getRotationMatrix2D( ( w/ 2 , h/ 2 ) , 45 , 1.0 )
rotation= cv2. warpAffine( image, M, ( w, h) )
show( rotation)
resize大小变换
width= 80
height= image. shape[ 0 ] * width// image. shape[ 1 ]
resize= cv2. resize( image, ( width, height) , interpolation= cv2. INTER_NEAREST)
show( resize)
画图
color= np. random. randint( 0 , 255 , size= ( 3 , ) ) . tolist( )
cv2. line( image, ( 0 , 0 ) , ( 300 , 300 ) , color, 5 )
cv2. rectangle( image, ( 10 , 10 ) , ( 100 , 100 ) , color, 3 )
cv2. circle( image, ( 150 , 150 ) , 100 , color, - 1 )
图像算术
image= imread( 'image.jpg' )
M= np. ones( image. shape, dtype= 'uint8' ) * 100
image= cv2. add( image, M)
image= cv2. subtract( image, M)
按位计算
black= np. zeros( [ 300 , 300 , 3 ] , dtype= 'uint8' )
rectangle= cv2. rectangle( black, ( 50 , 50 ) , ( 250 , 250 ) , ( 255 , 255 , 255 ) , - 1 )
show( rectangle)
circle= cv2. circle( black, ( 150 , 150 ) , 120 , ( 255 , 255 , 255 ) , - 1 )
show( circle)
image= cv2. bitwise_xor( rectangle, circle)
image= cv2. bitwise_and( rectangle, circle)
image= cv2. bitwise_or( rectangle, circle)
image= cv2. bitwise_not( circle)
切分合并通道
( R, G, B) = cv2. split( image)
merge= cv2. merge( [ R, G, B] )
```