图片的读取与展示
import cv2
# 二位参数,0 gray 1 color
img = cv2.imread('name.jpg',1)
# 一位参数 window name 二位参数为显示数据
cv2.imshow('image',img)
# 必须waitkey因为数据会一瞬消失,waitkey后才能展示
cv2.waitKey (0)
图片的写入与图片质量的设置
# 有损压缩
cv2.imwrite("new_name.jpg",img,[cv2.IMWRITE_JPEG_CHROMA_QUALITY])
# 无损压缩,能够设置图片透明度
cv2.imwrite("new_name.png",img,[cv2.IMWRITE_PNG_COMPRESSION,0])
# jpg压缩比高 0-100 png 压缩比低 0-9
更改图片像素点值
# 需要注意,在opencv中读取到的彩色图片通道返回值为bgr而不是rgb
(b,g,r)=img[100,100]
print(b,g,r)
# 更改一百个像素点值,需要注意图片的x,y轴
for i in range(1,100):
img[10+i,100]=(255,0,0)
cv2.imshow('image',img)
cv2.waitKey (0)
效果如下
图片缩放
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
mode = imginfo[2]
# 放大 缩放 等比例缩放 非等比例缩放
dstheight = int(height*0.5)
dstwidth = int(width*0.5)
# 最近邻域插值 双线性插值 像素关系重采样 立方插值
dst = cv2.resize(img,(dstheight,dstwidth))
最近邻域插值法算法实现(在原图抽取像素点复制到模板中)
import cv2
import numpy as np
img = cv2.imread('name.jpg',1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
mode = imginfo[2]
dstheight = int(height/2)
dstwidth = int(width/2)
dstimage = np.zeros((dstheight,dstwidth,3),np.uint8)
for i in range(0,height):
for j in range(0,dstwidth):
inew = int(i*(height*1.0/dstheight))
jnew = int(j*(width*1.0/dstwidth))
dstimage[i,j]=img[inew,jnew]
cv2.imshow("dst",dstimage)
cv2.waitKey(0)
图片的剪切
dst = img[100:200,100:300]
cv2.imshow('image',dst)
图片的位移
# 图片向左边位移
dst = np.zeros(img.shape,np.uint8)
height = imginfo[0]
width = imginfo[1]
for i in range(0,height):
for j in range(0,width-100):
dst[i,j+100]=img[i,j]
cv2.imshow("image",dst)
图片位移的另一种实现方式
# 向右移动100像素,向下移动200像素
matshift=np.float32([[1,0,100],[0,1,200]])
dst = cv2.warpAffine(img,matshift,(height,width))
图片镜像
newimginfo=(height*2,width,deep)
dst=np.zeros(newimginfo,np.uint8)
for i in range(0,height):
for j in range(0,width):
dst[i,j]=img[i,j]
dst[height*2-i-1,j]=img[i,j]
# 画镜像线
for i in range(0,width):
dst[height,i]=(0,0,255) #bgr
仿射变换
matsrc=np.float32([[0,0],[0,height-1],[width-1,0]])
matdst=np.float32([[50,50],[300,height-200],[width-300,100]])
# 获取仿射规律
mataffine=cv2.getAffineTransform(matsrc,matdst)
dst = cv2.warpAffine(img,mataffine,(width,height))
图片的旋转
# 参数一 旋转中心,参数二 旋转角度(逆时针),参数三 缩放比例
matrotate=cv2.getRotationMatrix2D((height*0.5,width*0.5),45,0.5)
dst = cv2.warpAffine(img,matRotate,(height,width))