图像处理python代码(自用)

1、二值图求差并计算比例

import cv2
import numpy as np
import os
from PIL import Image

# 需要输入图像的路径
img_path = "./gtFine/train/raw/"
mask_path = "./mask/train/"
imgROI_path = "./diff/train/"

if not os.path.exists(imgROI_path):
    os.makedirs(imgROI_path)

sum = 0
count = 0
for _image in os.listdir(img_path):
    if _image.split('.')[1] == "png":
        print(_image)
        # 将同名的图片和mask相减
        img_path_ = os.path.join(img_path, _image)
        portion = os.path.splitext(_image)
        #mask_name = portion[0] + "_color" + portion[1]
        mask_name = portion[0] + portion[1]
        mask_path_ = os.path.join(mask_path, mask_name)

        img = cv2.imread(img_path_)
        mask = cv2.imread(mask_path_)

        result1 = cv2.subtract(img, mask)
        result2 = cv2.subtract(mask, img)
        result = cv2.add(result1, result2)
        result = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)

        color = np.where(result == 255)[0].shape[0]
        pixel_sum = result.shape[0] * result.shape[1]

        sum += color / pixel_sum
        count += 1

        result = Image.fromarray(result)
        result.save(imgROI_path + _image)

print(1-sum/count)

2、孔洞填充及膨胀腐蚀操作

from PIL import Image
import os
import numpy as np
import cv2

img_path = './mask/train/'
result_path = './mask_result/train/'

# 先采用开运算去除小的噪点 然后膨胀 最后使用孔洞填充

# 孔洞填充
def im_fill(imgray):
    # 原图取补得到MASK图像
    mask = 255 - imgray

    # 构造Marker图像
    marker = np.zeros_like(imgray)
    marker[0, :] = 255
    marker[-1, :] = 255
    marker[:, 0] = 255
    marker[:, -1] = 255
    marker_0 = marker.copy()

    # 形态学重建
    SE = cv2.getStructuringElement(shape=cv2.MORPH_CROSS, ksize=(3, 3))
    while True:
        marker_pre = marker
        dilation = cv2.dilate(marker, kernel=SE)
        marker = np.min((dilation, mask), axis=0)
        if (marker_pre == marker).all():
            break
    dst = 255 - marker
    return dst


if not os.path.exists(result_path):
    os.makedirs(result_path)

for _image in os.listdir(img_path):
    print(_image)
    img_path_ = os.path.join(img_path, _image)
    img = cv2.imread(img_path_)

    # Use closing operate
    # closing_kernel = np.ones((20, 20), np.uint8)
    # img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, closing_kernel, iterations=2)
    # img = np.hstack((img, closing))

    # Use opening operate
    opening_kernel = np.ones((10, 10), np.uint8)
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, opening_kernel, iterations=1)
    # img = np.hstack((img, opening))

    # Use dilate operate
    dilate_kernel = np.ones((60, 60), np.uint8)
    img = cv2.dilate(img, dilate_kernel, iterations=1)

    img = im_fill(img)

    res_img = Image.fromarray(img)
    res_img.save(result_path + _image)

3、获取目录下所有图片像素值

from PIL import Image

import os


def checkColor(dir, file, recursion):
    files = os.listdir(dir)
    for name in files:
        fullname = os.path.join(dir, name)
        if (os.path.isdir(fullname) & recursion):
            checkColor(fullname, file, recursion)
        else:
            image = Image.open(fullname)
            file.write(name)
            file.write(str(image.getcolors()))
            file.write("\n")


def Test():
    dir = "./train"
    # txt文件名
    outfile = "train.txt"
    file = open(outfile, "w")
    checkColor(dir, file, 1)
    file.close()


Test()

4、高斯模糊

from PIL import Image, ImageFilter
# 打开图像
im1 = Image.open('iron_man.jpg')
# 创建一个im1两倍宽的图像
img = Image.new('RGB', (im1.width*2, im1.height), 'red')
# 高斯模糊处理
im2 = im1.filter(ImageFilter.GaussianBlur)
# 将im1粘贴到img上
img.paste(im1, (0, 0))
# 将im2(高斯模糊后的图像)粘贴到img上
img.paste(im2, (im1.width, 0))
img.show()

5、减法运算

from PIL import Image, ImageChops
# 打开图像
im1 = Image.open('xscn.jpg')
im2 = Image.open('xscn2.jpg')
# 合成图像并显示
im3 = ImageChops.subtract(im1, im2)
im3.show()

6、ImageEnhance模块(色彩、亮度)

from PIL import Image, ImageEnhance
# 打开im1
im1 = Image.open("gtx.jpg")
# 获取颜色(各种)调整器
enhance_im1 = ImageEnhance.Color(im1)
#enhance_im1 = ImageEnhance.Contrast(im1)
#enhance_im1 = ImageEnhance.Brightness(im1)
#enhance_im1 = ImageEnhance.Sharpness(im1)
# 减弱颜色(以及其它属性)
im2 = enhance_im1.enhance(0.5)
# 增强颜色(以及其它属性)
im3 = enhance_im1.enhance(1.5)

# 获取原图大小
w, h = im1.size
# 创建一个原图大小3倍的图片
img = Image.new("RGB", (w*3, h))
# 将减弱的图片放在最左边
img.paste(im2, (0, 0))
# 将原图放在中间
img.paste(im1, (w, 0))
# 将增强后的图片放在最右边
img.paste(im3, (w*2, 0))
# 显示图片
img.show()

7、图像缩小

#!/usr/bin/env python
# encoding: utf-8
"""
@author: H
@software: Pycharm
@file: ImageInterpolation.py
@time: 2020/10/16 8:28
"""


import os
import numpy as np
from PIL import Image

file_path = r'D:\postgraduate\first_year\数字图像处理\作业\homework1\practice1\image\jerry.jpg'
img = Image.open(file_path)  # 读取图片,格式为Image

# 把Image格式的图片转化为numpy格式进性图像处理
img = np.array(img, dtype=np.uint8)

height, width, mode = img.shape[0], img.shape[1], img.shape[2]  # 取出高、宽、通道数
print(height, width, mode)  # (275 183 3)

# 缩放的目标大小,这里以缩放为原图的1/2为例
desWidth = int(width * 0.5)
desHeight = int(height * 0.5)
desImage = np.zeros((desHeight, desWidth, mode), np.uint8)  # 定义一个目标图片代表的array,纯黑图片

# 像素填充
# 方法1:最近邻插值法
for des_x in range(0, desHeight):
    for des_y in range(0, desWidth):
        # 判断新像素点在原图中的像素点坐标
        src_x = int(des_x * (height/desHeight))
        src_y = int(des_y * (width/desWidth))

        desImage[des_x, des_y] = img[src_x, src_y]  # 填充
print(desImage.shape)
des_img = Image.fromarray(desImage)
des_img.save('./image/jerry.jpg')  # 图片另存为


8、图像放大

#!/usr/bin/env python
# encoding: utf-8
"""
@author: H
@software: Pycharm
@file: ImageInterpolation1.py
@time: 2020/10/17 20:31
"""

import os
import numpy as np
from PIL import Image

"""
    图像缩放常见三种方法的实现:
        - 最近邻插值法
        - 双线性插值法
        - 双立方插值法
"""


def Interpolation_NNI(filepath):
    """
        最近邻插值法(nearest neighbor interpolation)
    :param filepath:
    :return:
    """
    img = Image.open(file_path)  # 读取图片,格式为Image
    # img.show()  # 显示图片

    # 把Image格式的图片转化为numpy格式进性图像处理
    img = np.array(img, dtype=np.uint8)

    height, width, mode = img.shape[0], img.shape[1], img.shape[2]  # 取出高、宽、通道数
    print(height, width, mode)  # (275 183 3)

    # 缩放的目标大小,这里以缩放为原图的1/2为例
    desWidth = int(width * 0.5)
    desHeight = int(height * 0.5)
    desImage = np.zeros((desHeight, desWidth, mode), np.uint8)  # 定义一个目标图片代表的array,纯黑图片

    # 像素填充
    # 方法1:最近邻插值法
    for des_x in range(0, desHeight):
        for des_y in range(0, desWidth):
            # 判断新像素点在原图中的像素点坐标
            src_x = int(des_x * (height / desHeight))
            src_y = int(des_y * (width / desWidth))
            desImage[des_x, des_y] = img[src_x, src_y]  # 填充
    print(desImage.shape)
    des_img = Image.fromarray(desImage)
    des_img.save('./image/jerry.jpg')


def Interpolation_Bilinear(filepath, desHeight, desWidth):
    # 双线性插值法
    img = Image.open(filepath)  # 读取图片
    img = np.array(img, np.uint8)  # 转化为numpy数组
    desImageNumpy = np.zeros(img.shape, np.uint8)  # 生成一个大小相同的全0的numpy数组
    height, width, mode = img.shape[0], img.shape[1], img.shape[2]  # 高、宽、channel数

    # 找出目标位置在源图中的位置
    scale_x = float(width)/desWidth  # x轴缩放比例
    scale_y = float(height)/desHeight  # y轴缩放比例
    des_image = np.zeros((desHeight, desWidth, mode), np.uint8)
    for n in range(mode):
        for des_y in range(desHeight):
            for des_x in range(desWidth):
                # 确定四个近邻点坐标
                src_x = (des_x + 0.5) * scale_x - 0.5  #
                src_y = (des_y + 0.5) * scale_y - 0.5

                src_x_1 = int(np.floor(src_x))  #
                src_y_1 = int(np.floor(src_y))
                src_x_2 = min(src_x_1+1, width-1)  # 防止坐标点寻找溢出
                src_y_2 = min(src_y_1+1, height-1)
                # 两次x轴线性插值
                value_1 = (src_x_2 - src_x)*img[src_y_1, src_x_1, n]+(src_x - src_x_1)*img[src_y_1, src_x_2, n]
                value_2 = (src_x_2 - src_x)*img[src_y_2, src_x_1, n]+(src_x - src_x_1)*img[src_y_2, src_x_2, n]
                # y轴线性插值
                des_image[des_y, des_x, n] = (src_y_2 - src_y)*value_1 + (src_y - src_y_1)*value_2
    print(des_image.shape)
    des_img = Image.fromarray(des_image)
    des_img.save('./image/new_bilinear.jpg')


if __name__ == '__main__':
    file_path = r'D:\postgraduate\first_year\数字图像处理\作业\homework1\practice1\image\kobe1.jpg'
    Interpolation_Bilinear(file_path, int(183*2), int(275*2))  # 双线性插值法


9、numpy数值计算

import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

print x + y
print np.add(x, y)
# [[ 6.0  8.0]
#  [10.0 12.0]]矩阵加

print x - y
print np.subtract(x, y)
# [[-4.0 -4.0]
#  [-4.0 -4.0]]矩阵减

print x * y
print np.multiply(x, y)
# [[ 5.0 12.0]
#  [21.0 32.0]]矩阵乘

print x / y
print np.divide(x, y)
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]矩阵除

print np.sqrt(x)
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]矩阵开方


#和MATLAB不同,*是元素逐个相乘,而不是矩阵乘法。在Numpy中使用dot来进行矩阵乘法:

import numpy as np

x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])

# 矩阵乘法,输出219
print v.dot(w)
print np.dot(v, w)

# 矩阵乘法,输出[29 67]
print x.dot(v)
print np.dot(x, v)

# 矩阵乘法,输出
# [[19 22]
#  [43 50]]
print x.dot(y)
print np.dot(x, y)


#Numpy提供了很多计算数组的函数,其中最常用的一个是sum:
import numpy as np
x = np.array([[1,2],[3,4]])
print np.sum(x)  # 计算所有元素和; prints "10"
print np.sum(x, axis=0)  # 计算列元素和; prints "[4 6]"
print np.sum(x, axis=1)  # 计算行元素和; prints "[3 7]"

#除了计算,我们还常常改变数组或者操作其中的元素。其中将矩阵转置是常用的一个,在Numpy中,使用T来转置矩阵:

import numpy as np
x = np.array([[1,2], [3,4]])
print x    # Prints "[[1 2]
           #          [3 4]]"
print x.T  # Prints "[[1 3]
           #          [2 4]]"

10、边缘检测

if values['canny']:
    frame = cv2.Canny(frame, values['canny_slider_a'], values['canny_slider_b'])

11、轮廓检测

if values['contour']:
    hue = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    hue = cv2.GaussianBlur(hue, (21, 21), 1)
    hue = cv2.inRange(hue, np.array([values['contour_slider'], values['base_slider'], 40]),
                      np.array([values['contour_slider'] + 30, 255, 220]))
    cnts= cv2.findContours(hue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
    cv2.drawContours(frame, cnts, -1, (0, 0, 255), 2)

12、调节对比度

if values['enhance']:
    enh_val = values['enhance_slider'] / 40
    clahe = cv2.createCLAHE(clipLimit=enh_val, tileGridSize=(8, 8))
    lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
    lab[:, :, 0] = clahe.apply(lab[:, :, 0])
    frame = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)

13、阈值二值化

if values['thresh']:
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)[:, :, 0]
    frame = cv2.threshold(frame, values['thresh_slider'], 255, cv2.THRESH_BINARY)[1]

14、预处理合集

#图像剪裁与预处理
#图片的缩放
import cv2
import numpy as np
img=cv2.imread('02.jpg',1)
#shape中包含三个信息
# [0]:行数
# [1]:列数
# [2]:通道数
imgInfo=img.shape
height=imgInfo[0]
width=imgInfo[1]
deep=imgInfo[2]
print(deep)

#【1】放大 缩小
a=1.2
dstHeight=int(height*a)
dstWidth=int(width*a)
#放大缩小 涉及到图像的插值
#常见的插值 最近邻域差插值 双线性插值 立方插值
dst=cv2.resize(img,(dstWidth,dstHeight))
cv2.imshow('resizeimage',dst)

#【2】图像剪切
#[2.1]中间位置剪切
x_center=int((width/2))
y_center=int((height/2))
cutimg_median=img[x_center-200:x_center+200,y_center-200:y_center+200]
cv2.imshow('cut_media',cutimg_median)

#[2.2]任意位置剪切
cutimg_every=img[200:600,200:400]
cv2.imshow('cut_every',cutimg_every)

#【3】 图片位移
#设定平移矩阵
#矩阵讲解
#matshift拆成22的矩阵和21的矩阵
#A=[[1,0],[0,1]],B=[[100],[200]] C=[X,Y]
#A*C=B
#最终效果图像沿着x轴移动100,沿着y轴移动200;
matshift=np.float32([[1,0,200],[0,1,200]])

shiftimg=cv2.warpAffine(img,matshift,(height,width))
cv2.imshow('shiftimg',shiftimg)

#【4】图像镜像
#上下镜像
#空白图像的尺寸大小
newImgInfo=(height*2,width,deep)
#创建空白图片
samedst=np.zeros(newImgInfo,np.uint8)
#开始镜像
for i in range(0,height):
    for j in range(0,width):
        #samedst上部分像素写入
        samedst[i,j]=img[i,j]
        #samedst下部分像素写入
        samedst[height*2-i-1,j]=img[i,j]
#绘制镜像线
for i in range(0,width):
    samedst[height,i]=(0,0,255)
cv2.imshow('samedst',samedst)

#【5】仿射变化
#设定变化矩阵  根据三组对应点寻找仿射变化的矩阵
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)
affineImg=cv2.warpAffine(img,matAffine,(width,height))
cv2.imshow('affineImg',affineImg)

#【6】旋转变化
matRotate=cv2.getRotationMatrix2D((height*0.5,width*0.5),45,0.5)
rotateImg=cv2.warpAffine(img,matRotate,(height,width))
cv2.imshow('rotateImg',rotateImg)

cv2.waitKey(0)

(未完)

你可能感兴趣的:(python,图像处理,计算机视觉)