python——图像处理2(resize、翻转、二值化、gama变换、截取人脸)

1.图片resize
import cv2
import os

path='1/'
save_path='2/'
for file in os.listdir(path):
    if file.endswith('jpg'):
        print(file)
        img = cv2.imread(path+file)
        new_img = cv2.resize(img, (2480, 3260), interpolation=cv2.INTER_CUBIC)
        cv2.imwrite(save_path+file,new_img)

2.图像翻转
# encoding:utf-8

import cv2
image = cv2.imread("14.jpg")

# Flipped Horizontally 水平翻转
h_flip = cv2.flip(image, 1)
cv2.imwrite("girl-h.jpg", h_flip)

# Flipped Vertically 垂直翻转
v_flip = cv2.flip(image, 0)
cv2.imwrite("girl-v.jpg", v_flip)

# Flipped Horizontally & Vertically 水平垂直翻转
hv_flip = cv2.flip(image, -1)
cv2.imwrite("girl-hv.jpg", hv_flip)

3.1 图像二值化1
import cv2 as cv
import numpy as np

#全局阈值
def threshold_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)  #把输入图像灰度化
    #直接阈值化是对输入的单通道矩阵逐像素进行阈值分割。
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
    print("threshold value %s"%ret)
    cv.namedWindow("binary0", cv.WINDOW_NORMAL)
    cv.imshow("binary0", binary)

#局部阈值
def local_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)  #把输入图像灰度化
    #自适应阈值化能够根据图像不同区域亮度分布,改变阈值
    binary =  cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY, 25, 10)
    cv.namedWindow("binary1", cv.WINDOW_NORMAL)
    cv.imshow("binary1", binary)

#用户自己计算阈值
def custom_threshold(image):
    gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)  #把输入图像灰度化
    h, w =gray.shape[:2]
    m = np.reshape(gray, [1,w*h])
    mean = m.sum()/(w*h)
    print("mean:",mean)
    ret, binary =  cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
    cv.namedWindow("binary2", cv.WINDOW_NORMAL)
    cv.imshow("binary2", binary)

src = cv.imread('img/a1.jpg')
cv.namedWindow('input_image', cv.WINDOW_NORMAL) #设置为WINDOW_NORMAL可以任意缩放
cv.imshow('input_image', src)
threshold_demo(src)
local_threshold(src)
custom_threshold(src)
cv.waitKey(0)
cv.destroyAllWindows()

3.2 图像二值化2
# 图片二值化
from PIL import Image
img = Image.open('img/74.jpg')
 
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
threshold = 180
 
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
 
# 图片二值化
photo = Img.point(table, '1')
photo.save("img/test2.jpg")

4.图像gama变换
#!/usr/bin/python
# coding:utf-8

import cv2
import numpy as np

img = cv2.imread('img/1/a2.jpg',1)

img1 = np.power(img/float(np.max(img)), 1/1.5)
img2 = np.power(img/float(np.max(img)), 1.5)

cv2.imshow('src',img)
cv2.imshow('gamma=1/1.5',img1)
cv2.imshow('gamma=55.5',img2)
cv2.waitKey(0)

5.截取图像的人脸大头贴

#-*-coding:utf8-*-
import os
import cv2
import time
import shutil
 
def getAllPath(dirpath, *suffix):
    PathArray = []
    for r, ds, fs in os.walk(dirpath):
        for fn in fs:
            if os.path.splitext(fn)[1] in suffix:
                fname = os.path.join(r, fn)
                PathArray.append(fname)
    return PathArray
 
def readPicSaveFace_1(sourcePath,targetPath,invalidPath,*suffix):
    try:
        ImagePaths=getAllPath(sourcePath, *suffix)
 
        #对list中图片逐一进行检查,找出其中的人脸然后写到目标文件夹下
        count = 1
        # haarcascade_frontalface_alt.xml为库训练好的分类器文件,下载opencv,安装目录中可找到
        face_cascade = cv2.CascadeClassifier('D:\install\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml')
        for imagePath in ImagePaths:
            try:
                img = cv2.imread(imagePath)
 
                if type(img) != str:
                    faces = face_cascade.detectMultiScale(img, 1.1, 5)
                    if len(faces):
                        for (x, y, w, h) in faces:
                        # 设置人脸宽度大于16像素,去除较小的人脸
                            if w>=16 and h>=16:
                            # 以时间戳和读取的排序作为文件名称
                                listStr = [str(int(time.time())), str(count)]
                                fileName = ''.join(listStr)
                            # 扩大图片,可根据坐标调整
                                X = int(x)
                                W = min(int(x + w),img.shape[1])
                                Y = int(y)
                                H = min(int(y + h),img.shape[0])
 
                                f = cv2.resize(img[Y:H, X:W], (W-X,H-Y))
                                cv2.imwrite(targetPath+os.sep+'%s.jpg' % fileName, f)
                                count += 1
                                print  (imagePath + "have face")
                    #else:
                     #   shutil.move(imagePath, invalidPath)
            except:
                continue
    except IOError:
        print ("Error")
    else:
        print ('Find '+str(count-1)+' faces to Destination '+targetPath)
 
if __name__ == '__main__':
    invalidPath = r'img'
    sourcePath = r'img' 
    targetPath1 = r'img'
    readPicSaveFace_1(sourcePath,targetPath1,invalidPath,'.jpg','.JPG','png','PNG')
    

你可能感兴趣的:(图像处理)