本来想实现打开文件之后,对文件进行加噪声的处理的,略略改了点之前的代码出了点问题(代码如下:

import cv2
import random
import numpy as np
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")


def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file


def gasuss_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)

    return out


def sp_noise(image, prob):
    '''
    添加椒盐噪声
    prob:噪声比例
    '''

    output = np.zeros(image.shape, np.uint8)
    thres = 1 - prob

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]

    return output

file = clicked()
file = file[0]
img = Image.open(file)


# 添加椒盐噪声,噪声比例为 0.02
out1 = sp_noise(img, prob=0.02)

# 添加高斯噪声,均值为0,方差为0.01
out2 = gasuss_noise(img, mean=0, var=0.01)



photo = ImageTk.PhotoImage(out1)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

photo1 = ImageTk.PhotoImage(out2)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo1)
imglabel.grid(row=0, column=3, columnspan=3)

window.mainloop()

有如下报错:

打开文件的功能是OK的,但是后续操作就不行了。

参考:

https://blog.csdn.net/qq_39735053/article/details/94012604的评论区:

——题外话。程序里一般用的都是RGB数组,说没有shape属性也可能是这个图像根本不是数组。Image.open()的结果是RGB图像数据但是程序里用的是RGB数组,所以报错。 cv2.imread()的结果则是直接的BGR数组。

问题可能出现在两种打开方式得到的东西不一样,一个是数据一个是图片,因此对应搜索了一下。

参考:

https://blog.csdn.net/carlprilo/article/details/79105370

from PIL import Image
import numpy as np
img = Image.open("文件存储的绝对路径")
img_array = np.array(img)
arr1 = img_array[:]
print(arr1.shape)
for x in range(1,arr1.shape[0]):
    for y in range(1,arr1.shape[1]):
        a = img_array[x,y][0]
        b = img_array[x,y][1]
        c = img_array[x,y][2]
        arr1[x,y] = (0,0,c)


image1 = Image.fromarray(arr1)
image1.show()

输出:

(600, 800, 3)

(题外话,这个画风……额)

______________________________________________________________________

附录:

arr1[x,y] = (0,0,c)修改这里会有变化(应该就是RGB,不然把c放出来不会这么蓝的,搞的我要原地去世了)

这里把其他组合都放一下(不能我一个人去世!!!!!!!!)

arr1[x,y] = (0,b,0)

arr1[x,y] = (a,0,0)

arr1[x,y] = (a,b,c)

arr1[x,y] = (a,b,0)

arr1[x,y] = (a,0,c)

arr1[x,y] = (0,b,c)

 

———————————虽然看起来很厉害,但是还是没啥用———————————

考虑到反正是格式问题,只要能把格式改好应该就大丈夫了

参考:

https://yuki-ho.blog.csdn.net/article/details/78367617?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-9.control&dist_request_id=1328741.37914.16169849679744717&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-9.control

import cv2
from PIL import Image


img = cv2.imread("……图片存储位置……/starry-night.jpg")
cv2.imshow("OpenCV", img)
image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
image.show()
cv2.waitKey()

输出:

按照参考的博客中的步骤,只要先在读入的时候转成opencv格式

在添加完成噪声之后,再把opencv格式转换成PIL.Image格式就OK了

代码:

import cv2
import random
import numpy
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")


def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file


def gasuss_noise(image, mean=0, var=0.001):
    '''
        添加高斯噪声
        mean : 均值
        var : 方差
    '''

    image = numpy.array(image / 255, dtype=float)
    noise = numpy.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = numpy.clip(out, low_clip, 1.0)
    out = numpy.uint8(out * 255)

    return out


def sp_noise(image, prob):
    '''
    添加椒盐噪声
    prob:噪声比例
    '''

    output = numpy.zeros(image.shape, numpy.uint8)
    thres = 1 - prob

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]

    return output

file = clicked()
file = file[0]
img = Image.open(file)

Img = cv2.cvtColor(numpy.asarray(img),cv2.COLOR_RGB2BGR)


# 添加椒盐噪声,噪声比例为 0.02
out1 = sp_noise(Img, prob=0.02)

# 添加高斯噪声,均值为0,方差为0.01
out2 = gasuss_noise(Img, mean=0, var=0.01)

image1 = Image.fromarray(cv2.cvtColor(out1,cv2.COLOR_BGR2RGB))
image2 = Image.fromarray(cv2.cvtColor(out2,cv2.COLOR_BGR2RGB))

photo = ImageTk.PhotoImage(image1)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

photo1 = ImageTk.PhotoImage(image2)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo1)
imglabel.grid(row=0, column=3, columnspan=3)

window.mainloop()

输出:

成功✓

 

把原始图像和灰度图像都放出来,调一下大小(此处见有关Python的图形化界面——tkinter):

import cv2
import random
import numpy
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")


def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file


def gasuss_noise(image, mean=0, var=0.001):
    '''
        添加高斯噪声
        mean : 均值
        var : 方差
    '''

    image = numpy.array(image / 255, dtype=float)
    noise = numpy.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = numpy.clip(out, low_clip, 1.0)
    out = numpy.uint8(out * 255)

    return out


def sp_noise(image, prob):
    '''
    添加椒盐噪声
    prob:噪声比例
    '''

    output = numpy.zeros(image.shape, numpy.uint8)
    thres = 1 - prob

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]

    return output

file = clicked()
file = file[0]
img = Image.open(file)

Img = cv2.cvtColor(numpy.asarray(img),cv2.COLOR_RGB2BGR)


# 添加椒盐噪声,噪声比例为 0.02
out1 = sp_noise(Img, prob=0.02)

# 添加高斯噪声,均值为0,方差为0.01
out2 = gasuss_noise(Img, mean=0, var=0.01)

image1 = Image.fromarray(cv2.cvtColor(out1,cv2.COLOR_BGR2RGB))
image2 = Image.fromarray(cv2.cvtColor(out2,cv2.COLOR_BGR2RGB))

image1 = image1.resize((400,300))
image2 = image2.resize((400,300))

photo = ImageTk.PhotoImage(image1)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

photo1 = ImageTk.PhotoImage(image2)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo1)
imglabel.grid(row=0, column=3, columnspan=3)

Img = img.convert('L')
img = img.resize((400,300))
Img = Img.resize((400,300))

Origphoto = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=Origphoto)
imglabel.grid(row=3, column=0, columnspan=3)

Greyphoto = ImageTk.PhotoImage(Img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=Greyphoto)
imglabel.grid(row=3, column=3, columnspan=3)


window.mainloop()

输出:

 

 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐