批量操作
#对文件进行批量重命名
import os
path=“C:\Users\Lenovo\Desktop/first.text”
filelist = os.listdir(path)
i = 0
for file in filelist:
old = os.path.join(path,file)
filetype = os.path.splitext(file)[1]
i = i+1;
new = os.path.join(path,str(i)+filetype)
os.rename(old,new)
读取图片
>>> import cv2 #导入opencv包
>>> img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg') #绝对路径,这里为'/'
>>> cv2.imshow('test',img)
>>> cv2.waitKey(0) #让图像不会一闪而过
保存图片
import cv2
>>> img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
>>> cv2.imshow('test',img)
>>> cv2.imwrite('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.png',img) #将图片转换为png格式保存
True
>>> cv2.imwrite('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.bmp',img)#将图片转换为bmp格式保存
True
>>> cv2.waitKey(0)
截取图像
import cv2
>>> img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
>>> frame=img[300:600,300:600] #截取部分图像为300:600行,300:600
>>> cv2.imshow('test',frame)
>>> cv2.waitKey(0)
翻转图片
通过flipcode控制图片翻转方向
import cv2
img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
flipcode1=1 #大于0时图片左右翻转
flipcode2=0 #等于0时上下翻转
flipcode3=-1 #小于0时先上下再左右翻转
img1=cv2.flip(img,flipcode1)
img2=cv2.flip(img,flipcode2)
img3=cv2.flip(img,flipcode3)
cv2.imshow('test1',img1)
cv2.imshow('test2',img2)
cv2.imshow('test3',img3)
cv2.waitKey(0)
图片的缩放
import cv2
img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
img1=cv2.resize(img,(600,600))
img2=cv2.resize(img,None,fx=0.6,fy=0.6) #None的位置原本用于输出尺寸,现在设置缩放因子fx(水平轴),fy(竖直轴).
cv2.imshow('test',img)
cv2.imshow('test1',img1)
cv2.imshow('test2',img2)
cv2.imwrite('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg',img1)
cv2.waitKey(0)
转换为灰度图像
import cv2
img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
cv2.imshow('BGR',img)
img1=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #将图像格式转换为RGB,但opencv按照BGR读取图片,故转换为RGB后不像原图
cv2.imshow('RGB',img1)
img2=cv2.cvtColor(img1,cv2.COLOR_RGB2GRAY) #将图像转换为灰度图像
cv2.imshow('GRAY',img2)
cv2.waitKey(0)
在一个窗口中显示两张图片
import cv2
import numpy as np
img=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
img1=cv2.imread('D:/Peggy/v2-a71a40410bbc2789cc3f1c0cad413bb8_r.jpg')
imgs=np.hstack([img,img1]) #水平方向
#imgs=np.vstack([img,img1]) #竖直方向
cv2.imshow('mutil_pic',imgs)
cv2.waitKey(0)
文章评论