python读取保存多帧图片数量少了

Python052

python读取保存多帧图片数量少了,第1张

cv2.imshow("left", img_left)

filename3=str(number)+'n3'+'.jpg' #打印第number张图片+增值方式+保存类型

cv2.imwrite(savedpath + filename3, img_left)

"""

# 数据增强实现

"""

import cv2

import numpy as np

import os

# 图像平移

def img_translation(image):

# 图像平移 下、上、右、左平移

M = np.float32([[1, 0, 0], [0, 1, 100]])

img_down = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, 0], [0, 1, -100]])

img_up = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, 100], [0, 1, 0]])

img_right = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

M = np.float32([[1, 0, -100], [0, 1, 0]])

img_left = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))

# 保存图片,需要保存上述的哪一图片,就在cv2.imwrite()中,将哪一图片名放入。

# filename='xxx' +'.jpeg'

# cv2.imwrite(savedpath + filename, img_left)

# 显示图形

cv2.imshow("down", img_down)

filename0=str(number)+'n0'+'.jpg'

cv2.imwrite(savedpath + filename0, img_down)

cv2.imshow("up", img_up)

filename1=str(number)+'n1'+'.jpg'

cv2.imwrite(savedpath + filename1, img_up)

cv2.imshow("right", img_right)

filename2=str(number)+'n2'+'.jpg'

cv2.imwrite(savedpath + filename2, img_right)

cv2.imshow("left", img_left)

filename3=str(number)+'n3'+'.jpg'

cv2.imwrite(savedpath + filename3, img_left)

# 图像缩放

def img_scale(image):

result = cv2.resize(image, (224, 224))

cv2.imshow("scale", result)

filename=str(number)+'n5'+'.jpg'

cv2.imwrite(savedpath + filename, result)

# 图像翻转

def img_flip(image):

# 0以X轴为对称轴翻转,>0以Y轴为对称轴翻转, <0X轴Y轴翻转

horizontally = cv2.flip(image, 0) # 水平镜像

vertically = cv2.flip(image, 1) # 垂直镜像

hv = cv2.flip(image, -1) # 水平垂直镜像

# 显示图形

cv2.imshow("Horizontally", horizontally)

filename1=str(number)+'n6'+'.jpg'

cv2.imwrite(savedpath + filename1, horizontally)

cv2.imshow("Vertically", vertically)

filename2=str(number)+'n7'+'.jpg'

cv2.imwrite(savedpath + filename2, vertically)

cv2.imshow("Horizontally &Vertically", hv)

filename3=str(number)+'n8'+'.jpg'

cv2.imwrite(savedpath + filename3, hv)

# 图像旋转

def img_rotation(image):

# 原图的高、宽 以及通道数

rows, cols, channel = image.shape

# 绕图像的中心旋转

# 参数:旋转中心 旋转度数 scale

M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 30, 1)

# 参数:原始图像 旋转参数 元素图像宽高

rotated = cv2.warpAffine(image, M, (cols, rows))

# 显示图像

cv2.imshow("rotated", rotated)

filename1=str(number)+'n9'+'.jpg'

cv2.imwrite(savedpath + filename1, rotated)

#选装60度

W = cv2.getRotationMatrix2D((cols / 2, rows / 2), 60, 1)

# 参数:原始图像 旋转参数 元素图像宽高

rotated1 = cv2.warpAffine(image, W, (cols, rows))

cv2.imshow("rotated", rotated)

filename2=str(number)+'n12'+'.jpg'

cv2.imwrite(savedpath + filename2, rotated1)

#选装145度

W = cv2.getRotationMatrix2D((cols / 2, rows / 2), 60, 1)

# 参数:原始图像 旋转参数 元素图像宽高

rotated2 = cv2.warpAffine(image, W, (cols, rows))

cv2.imshow("rotated", rotated)

filename3=str(number)+'n13'+'.jpg'

cv2.imwrite(savedpath + filename3, rotated2)

# 图像加噪

def img_noise(image, mean=0, var=0.001):

'''

添加高斯噪声

mean : 均值

var : 方差

'''

image = np.array(image / 255, dtype=float)

noise = np.random.normal(mean, var ** 0.5, image.shape)

out = image + noise

if out.min() <0:

low_clip = -1.

else:

low_clip = 0.

out = np.clip(out, low_clip, 1.0)

out = np.uint8(out * 255)

cv2.imshow("noise", out)

filename3=str(number)+'n10'+'.jpg'

cv2.imwrite(savedpath + filename3, out)

# 图像亮度调节

def img_brightness(image):

contrast = 1 # 对比度

brightness = 100 # 亮度

pic_turn = cv2.addWeighted(image, contrast, image, 0, brightness)

# cv2.addWeighted(对象,对比度,对象,对比度)

'''cv2.addWeighted()实现的是图像透明度的改变与图像的叠加'''

cv2.imshow('bright', pic_turn) # 显示图片

filename3=str(number)+'n11'+'.jpg'

cv2.imwrite(savedpath + filename3, pic_turn)

if __name__ == '__main__':

i = 0

path = '../Data/'

print(path)

savedpath = './result_new/'

filelist = os.listdir(path)

total_num = len(filelist)

for item in filelist:

number = i + 1

i = number

print("######")

print("打印到第",i,"张图片")

src = cv2.imread(path + item)

img_translation(src)

img_scale(src)

img_flip(src)

img_rotation(src)

img_noise(src)

img_brightness(src)

cv2.waitKey(0)

cv2.destroyAllWindows()

代码较为繁琐,有空之后进行优化

输出结果

如何用python实现图像的一维高斯滤波器

现在把卷积模板中的值换一下,不是全1了,换成一组符合高斯分布的数值放在模板里面,比如这时中间的数值最大,往两边走越来越小,构造一个小的高斯包。实现的函数为cv2.GaussianBlur()。对于高斯模板,我们需要制定的是高斯核的高和宽(奇数),沿x与y方向的标准差(如果只给x,y=x,如果都给0,那么函数会自己计算)。高斯核可以有效的出去图像的高斯噪声。当然也可以自己构造高斯核,相关函数:cv2.GaussianKernel().

import cv2

import numpy as np

import matplotlib.pyplot as plt

img = cv2.imread(‘flower.jpg‘,0) #直接读为灰度图像

for i in range(2000): #添加点噪声

temp_x = np.random.randint(0,img.shape[0])

temp_y = np.random.randint(0,img.shape[1])

img[temp_x][temp_y] = 255

blur = cv2.GaussianBlur(img,(5,5),0)

plt.subplot(1,2,1),plt.imshow(img,‘gray‘)#默认彩色,另一种彩色bgr

plt.subplot(1,2,2),plt.imshow(blur,‘gray‘)

import CV2

import copy

import numpy as np

import random

使用的是pycharm

因为最近看了《银翼杀手2049》,里面Joi实在是太好看了所以原图像就用Joi了

要求是灰度图像,所以第一步先把图像转化成灰度图像

# 读入原始图像

img = CV2.imread('joi.jpg')

# 灰度化处理

gray = CV2.cvtColor(img, CV2.COLOR_BGR2GRAY)

CV2.imwrite('img.png', gray)

第一个任务是利用分段函数增强灰度对比,我自己随便写了个函数大致是这样的

def chng(a):

if a <255/3:

b = a/2

elif a <255/3*2:

b = (a-255/3)*2 + 255/6

else:

b = (a-255/3*2)/2 + 255/6 +255/3*2

return b

rows = img.shape[0]

cols = img.shape[1]

cover = copy.deepcopy(gray)

for i in range(rows):

for j in range(cols):

cover[i][j] = chng(cover[i][j])

CV2.imwrite('cover.png', cover)

下一步是直方图均衡化

# histogram equalization

def hist_equal(img, z_max=255):

H, W = img.shape

# S is the total of pixels

S = H * W * 1.

out = img.copy()

sum_h = 0.

for i in range(1, 255):

ind = np.where(img == i)

sum_h += len(img[ind])

z_prime = z_max / S * sum_h

out[ind] = z_prime

out = out.astype(np.uint8)

return out

covereq = hist_equal(cover)

CV2.imwrite('covereq.png', covereq)

在实现滤波之前先添加高斯噪声和椒盐噪声(代码来源于网络)

不知道这个椒盐噪声的名字是谁起的感觉隔壁小孩都馋哭了

用到了random.gauss()

percentage是噪声占比

def GaussianNoise(src,means,sigma,percetage):

NoiseImg=src

NoiseNum=int(percetage*src.shape[0]*src.shape[1])

for i in range(NoiseNum):

randX=random.randint(0,src.shape[0]-1)

randY=random.randint(0,src.shape[1]-1)

NoiseImg[randX, randY]=NoiseImg[randX,randY]+random.gauss(means,sigma)

if NoiseImg[randX, randY]<0:

NoiseImg[randX, randY]=0

elif NoiseImg[randX, randY]>255:

NoiseImg[randX, randY]=255

return NoiseImg

def PepperandSalt(src,percetage):

NoiseImg=src

NoiseNum=int(percetage*src.shape[0]*src.shape[1])

for i in range(NoiseNum):

randX=random.randint(0,src.shape[0]-1)

randY=random.randint(0,src.shape[1]-1)

if random.randint(0,1)<=0.5:

NoiseImg[randX,randY]=0

else:

NoiseImg[randX,randY]=255

return NoiseImg

covereqg = GaussianNoise(covereq, 2, 4, 0.8)

CV2.imwrite('covereqg.png', covereqg)

covereqps = PepperandSalt(covereq, 0.05)

CV2.imwrite('covereqps.png', covereqps)

下面开始均值滤波和中值滤波了

就以n x n为例,均值滤波就是用这n x n个像素点灰度值的平均值代替中心点,而中值就是中位数代替中心点,边界点周围补0;前两个函数的作用是算出这个点的灰度值,后两个是对整张图片进行

#均值滤波模板

def mean_filter(x, y, step, img):

sum_s = 0

for k in range(x-int(step/2), x+int(step/2)+1):

for m in range(y-int(step/2), y+int(step/2)+1):

if k-int(step/2) 0 or k+int(step/2)+1 >img.shape[0]

or m-int(step/2) 0 or m+int(step/2)+1 >img.shape[1]:

sum_s += 0

else:

sum_s += img[k][m] / (step*step)

return sum_s

#中值滤波模板

def median_filter(x, y, step, img):

sum_s=[]

for k in range(x-int(step/2), x+int(step/2)+1):

for m in range(y-int(step/2), y+int(step/2)+1):

if k-int(step/2) 0 or k+int(step/2)+1 >img.shape[0]

or m-int(step/2) 0 or m+int(step/2)+1 >img.shape[1]:

sum_s.append(0)

else:

sum_s.append(img[k][m])

sum_s.sort()

return sum_s[(int(step*step/2)+1)]

def median_filter_go(img, n):

img1 = copy.deepcopy(img)

for i in range(img.shape[0]):

for j in range(img.shape[1]):

img1[i][j] = median_filter(i, j, n, img)

return img1

def mean_filter_go(img, n):

img1 = copy.deepcopy(img)

for i in range(img.shape[0]):

for j in range(img.shape[1]):

img1[i][j] = mean_filter(i, j, n, img)

return img1

完整main代码如下:

if __name__ == "__main__":

# 读入原始图像

img = CV2.imread('joi.jpg')

# 灰度化处理

gray = CV2.cvtColor(img, CV2.COLOR_BGR2GRAY)

CV2.imwrite('img.png', gray)

rows = img.shape[0]

cols = img.shape[1]

cover = copy.deepcopy(gray)

for i in range(rows):

for j in range(cols):

cover[i][j] = chng(cover[i][j])

CV2.imwrite('cover.png', cover)

covereq = hist_equal(cover)

CV2.imwrite('covereq.png', covereq)

covereqg = GaussianNoise(covereq, 2, 4, 0.8)

CV2.imwrite('covereqg.png', covereqg)

covereqps = PepperandSalt(covereq, 0.05)

CV2.imwrite('covereqps.png', covereqps)

meanimg3 = mean_filter_go(covereqps, 3)

CV2.imwrite('medimg3.png', meanimg3)

meanimg5 = mean_filter_go(covereqps, 5)

CV2.imwrite('meanimg5.png', meanimg5)

meanimg7 = mean_filter_go(covereqps, 7)

CV2.imwrite('meanimg7.png', meanimg7)

medimg3 = median_filter_go(covereqg, 3)

CV2.imwrite('medimg3.png', medimg3)

medimg5 = median_filter_go(covereqg, 5)

CV2.imwrite('medimg5.png', medimg5)

medimg7 = median_filter_go(covereqg, 7)

CV2.imwrite('medimg7.png', medimg7)

medimg4 = median_filter_go(covereqps, 7)

CV2.imwrite('medimg4.png', medimg4)