Создание негативного изображения в Python: несколько методов инверсии изображения

В Python существует несколько методов создания негативного изображения. Вот несколько методов, которые вы можете использовать:

  1. Использование модуля PIL (библиотека изображений Python):

    from PIL import Image
    def create_negative_image(image_path):
    # Open the image
    image = Image.open(image_path)
    
    # Invert the image
    inverted_image = Image.eval(image, lambda pixel: 255 - pixel)
    
    # Show or save the inverted image
    inverted_image.show()  # Or inverted_image.save('negative_image.png')
    # Usage
    create_negative_image('image.png')
  2. Использование OpenCV:

    import cv2
    def create_negative_image(image_path):
    # Read the image
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    
    # Invert the image
    inverted_image = cv2.bitwise_not(image)
    
    # Show or save the inverted image
    cv2.imshow('Negative Image', inverted_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    # Usage
    create_negative_image('image.png')
  3. Использование NumPy:

    import numpy as np
    import matplotlib.pyplot as plt
    def create_negative_image(image_path):
    # Read the image
    image = plt.imread(image_path)
    
    # Invert the image
    inverted_image = 1 - image
    
    # Show or save the inverted image
    plt.imshow(inverted_image)
    plt.axis('off')
    plt.show()
    # Usage
    create_negative_image('image.png')