如何在Python中交换图像中的随机像素?

时间:2019-04-25 18:59:53

标签: python image pixel

我正在尝试编写一个程序,该程序随机交换图像中的像素以使其全新。我正在为行和列生成两组随机值,​​然后要交换图像的那些像素。

但是由于某种原因,我的代码无法实现我想要的功能。图像看起来与原始图片相对相似,但是看起来有点模糊。

我希望最终结果是相同的图片,但某些(或全部)像素随机放置在不同的位置。

     def get_pixel(image, i, j):
     # Inside image bounds?
       width, height = image.size
       if i > width or j > height:
       return None

     # Get Pixel
       pixel = image.getpixel((i, j))
       return pixel

     from PIL import Image
     from argparse import ArgumentParser
     import random as r

     parser = ArgumentParser()

     parser.add_argument("-p",dest="picture",  
                help="write the name of the photo with the file type") 

     args= parser.parse_args()

      image = Image.open(args.picture)

     # Get size
     width, height = image.size

     pixels = image.load()

      ran1 = r.randint(0, width-1)
      ran2 = r.randint(0, height-1)

     for i in range(ran1):
        for j in range(ran2):
         # Get Pixel
         rand1 = r.randint(0, width-1)
         rand2 = r.randint(0, height-1)

         rand3 = r.randint(0, width-1)
         rand4 = r.randint(0, height-1)

         pixel = get_pixel(image, rand1, rand2)
         pixel2 = get_pixel(image, rand3, rand4)

        # Set Pixel in new image
         pixels[rand1, rand2] = (pixel2[0], pixel2[1],pixel2[2])
         pixels[rand3, rand4] = (pixel[0], pixel[1],pixel[2])

        # Return new image
  image.save('lol.png', 'png')

0 个答案:

没有答案