1、职业照–蓝底照片转换为白底
import cv2
import numpy as np
img=cv2.imread('C:/Users/Desktop/1.jpg')
rows,cols,channels = img.shape
img=cv2.resize(img,None,fx=0.5,fy=0.5)
rows,cols,channels = img.shape
cv2.imshow('img',img)
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower_blue=np.array([78,43,46])
upper_blue=np.array([110,255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
erode=cv2.erode(mask,None,iterations=1)
dilate=cv2.dilate(erode,None,iterations=1)
for i in range(rows):
for j in range(cols):
if dilate[i,j]==255:
img[i, j] = (0, 0, 255)
cv2.imwrite('C:/Users/Desktop/red.jpg',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2、将bmp格式的图片批量转成jpg
import os
import cv2
bmp_dir = 'C:/Users/Desktop/Data'
jpg_dir = 'C:/Users/Desktop/Data1'
filelists = os.listdir(bmp_dir)
for i,file in enumerate(filelists):
img = cv2.imread(os.path.join(bmp_dir,file),-1)
newName = file.replace('.bmp','.jpg')
cv2.imwrite(os.path.join(jpg_dir,newName),img)
print('第%d张图:%s'%(i+1,newName))
3、将批量图片合成一段视频
import os
import cv2
file_dir='E:/project_python/opencv_python/pic1/'
list=[]
for root,dirs,files in os.walk(file_dir):
for file in files:
list.append(file)
video=cv2.VideoWriter('E:/project_python/opencv_python/pic1/test.avi',cv2.VideoWriter_fourcc(*'MJPG'),10,(1280,720))
for i in range(1,len(list)):
img=cv2.imread('E:/project_python/opencv_python/pic1/'+list[i-1])
img=cv2.resize(img,(1280,720))
video.write(img)
video.release()
4、将一段视频处理成批量图片
import cv2
mp4 = cv2.VideoCapture("video.mp4")
is_opened = mp4.isOpened()
print(is_opened)
fps = mp4.get(cv2.CAP_PROP_FPS)
print(fps)
widght = mp4.get(cv2.CAP_PROP_FRAME_WIDTH)
height = mp4.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(str(widght) + "x" + str(height))
i = 0
while is_opened:
if i == 13:
break
else:
i += 1
(flag, frame) = mp4.read()
file_name = "iamge" + str(i) + ".jpg"
print(file_name)
if flag == True:
cv2.imwrite(file_name, frame, [cv2.IMWRITE_JPEG_QUALITY])
print("转换完成")
5、两张图片叠加放在一起,调整透明度
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img1= cv.imread('C:/Users/Desktop/1.jpg')
img2= cv.imread('C:/Users/Desktop/2.jpg')
dst = cv.addWeighted(img1,0.62,img2,0.38,0)
cv.imshow('new_pic',dst)
cv.waitKey(0)
cv.destroyAllWindows()
![在这里插入图片描述](https://img-blog.csdnimg.cn/41bc41afc266475da03c8dc7c239f4db.jpeg#pic_center)
6、数据增强
"""数据增强
1. 翻转变换 flip
2. 随机修剪 random crop
3. 色彩抖动 color jittering
4. 平移变换 shift
5. 尺度变换 scale
6. 对比度变换 contrast
7. 噪声扰动 noise
8. 旋转变换/反射变换 Rotation/reflection
"""
from PIL import Image, ImageEnhance, ImageOps, ImageFile
import numpy as np
import random
import threading, os, time
import logging
logger = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = True
class DataAugmentation:
"""
包含数据增强的八种方式
"""
def __init__(self):
pass
@staticmethod
def openImage(image):
return Image.open(image, mode="r")
@staticmethod
def randomRotation(image, mode=Image.BICUBIC):
"""
对图像进行随机任意角度(0~360度)旋转
:param mode 邻近插值,双线性插值,双三次B样条插值(default)
:param image PIL的图像image
:return: 旋转转之后的图像
"""
random_angle = np.random.randint(1, 360)
return image.rotate(random_angle, mode)
@staticmethod
def randomCrop(image):
"""
对图像随意剪切,考虑到图像大小范围(68,68),使用一个一个大于(36*36)的窗口进行截图
:param image: PIL的图像image
:return: 剪切之后的图像
"""
image_width = image.size[0]
image_height = image.size[1]
crop_win_size = np.random.randint(40, 68)
random_region = (
(image_width - crop_win_size) >> 1, (image_height - crop_win_size) >> 1, (image_width + crop_win_size) >> 1,
(image_height + crop_win_size) >> 1)
return image.crop(random_region)
@staticmethod
def randomColor(image):
"""
对图像进行颜色抖动
:param image: PIL的图像image
:return: 有颜色色差的图像image
"""
random_factor = np.random.randint(0, 31) / 10.
color_image = ImageEnhance.Color(image).enhance(random_factor)
random_factor = np.random.randint(10, 21) / 10.
brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor)
random_factor = np.random.randint(10, 21) / 10.
contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor)
random_factor = np.random.randint(0, 31) / 10.
return ImageEnhance.Sharpness(contrast_image).enhance(random_factor)
@staticmethod
def randomGaussian(image, mean=0.2, sigma=0.3):
"""
对图像进行高斯噪声处理
:param image:
:return:
"""
def gaussianNoisy(im, mean=0.2, sigma=0.3):
"""
对图像做高斯噪音处理
:param im: 单通道图像
:param mean: 偏移量
:param sigma: 标准差
:return:
"""
for _i in range(len(im)):
im[_i] += random.gauss(mean, sigma)
return im
img = np.asarray(image)
img.flags.writeable = True
width, height = img.shape[:2]
img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma)
img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma)
img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma)
img[:, :, 0] = img_r.reshape([width, height])
img[:, :, 1] = img_g.reshape([width, height])
img[:, :, 2] = img_b.reshape([width, height])
return Image.fromarray(np.uint8(img))
@staticmethod
def saveImage(image, path):
image.save(path)
def makeDir(path):
try:
if not os.path.exists(path):
if not os.path.isfile(path):
os.makedirs(path)
return 0
else:
return 1
except Exception as e:
print(str(e))
return -2
def imageOps(func_name, image, des_path, file_name, times=5):
funcMap = {"randomRotation": DataAugmentation.randomRotation,
"randomCrop": DataAugmentation.randomCrop,
"randomColor": DataAugmentation.randomColor,
"randomGaussian": DataAugmentation.randomGaussian
}
if funcMap.get(func_name) is None:
logger.error("%s is not exist", func_name)
return -1
for _i in range(0, times, 1):
new_image = funcMap[func_name](image)
DataAugmentation.saveImage(new_image, os.path.join(des_path, func_name + str(_i) + file_name))
opsList = {"randomRotation", "randomCrop", "randomColor", "randomGaussian"}
def threadOPS(path, new_path):
"""
多线程处理事务
:param src_path: 资源文件
:param des_path: 目的地文件
:return:
"""
if os.path.isdir(path):
img_names = os.listdir(path)
print("------------------")
else:
img_names = [path]
img_names = os.listdir(path)
print("==================")
for img_name in img_names:
print(img_name)
tmp_img_name = os.path.join(path, img_name)
print("+++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(tmp_img_name)
print(tmp_img_name.split('.'))
if os.path.isdir(tmp_img_name):
if makeDir(os.path.join(new_path, img_name)) != -1:
threadOPS(tmp_img_name, os.path.join(new_path, img_name))
else:
print('create new dir failure')
return -1
elif tmp_img_name.split('.')[1] != "DS_Store":
image = DataAugmentation.openImage(tmp_img_name)
threadImage = [0] * 5
_index = 0
for ops_name in opsList:
threadImage[_index] = threading.Thread(target=imageOps,
args=(ops_name, image, new_path, img_name,))
threadImage[_index].start()
_index += 1
time.sleep(0.2)
if __name__ == '__main__':
threadOPS("C:/Users/Desktop/Data1", "C:/Users/out_img1")
7、画图
画图一
import numpy as np
import cv2 as cv
img = np.zeros((512,512,3), np.uint8)
cv.line(img,(0,0),(511,511),(255,0,0),5)
cv.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv.circle(img,(447,63), 63, (0,0,255), -1)
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv.polylines(img,[pts],True,(0,255,255))
cv.imshow('image', img)
cv.waitKey(0)
cv.destroyAllWindows()
画图二
import numpy as np
import cv2 as cv
def draw_circle(event,x,y,flags,param):
if event == cv.EVENT_LBUTTONDBLCLK:
cv.circle(img,(x,y),100,(255,0,0),-1)
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv.imshow('image',img)
if cv.waitKey(20) & 0xFF == 27:
break
cv.destroyAllWindows()
画图三
import numpy as np
import cv2 as cv
drawing = False
mode = True
ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv.circle(img,(x,y),5,(0,0,255),-1)
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv.destroyAllWindows()
画图四
import numpy as np
import cv2 as cv
def nothing(x):
pass
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,nothing)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
r = cv.getTrackbarPos('R','image')
g = cv.getTrackbarPos('G','image')
b = cv.getTrackbarPos('B','image')
s = cv.getTrackbarPos(switch,'image')
if s == 0:
img[:] = 0
else:
img[:] = [b,g,r]
cv.destroyAllWindows()
画图五
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
BLUE = [255,0,0]
img1 = cv.imread('C:/Users/Desktop/1.jpg')
replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE)
reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT)
reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101)
wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP)
constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show()