Python Pillow - ImageChops.logical_and() 函式



PIL.ImageChops.logical_and() 函式執行兩個輸入影像對應畫素之間的邏輯與運算。兩個輸入影像都必須具有“1”模式,表示二進位制(黑白)影像。如果打算對模式不是“1”的影像執行邏輯與運算,則可以使用 multiply() 函式,並提供黑白蒙版作為第二個影像。

該運算定義如下:

$$\mathrm{out\:=\:((image1\:and\:image2)\:\%\:MAX)}$$

語法

以下是該函式的語法:

PIL.ImageChops.logical_and(image1, image2)

引數

以下是該函式引數的詳細資訊:

  • image1 - 第一個模式為“1”的二進位制輸入影像。

  • image2 - 第二個模式為“1”的二進位制輸入影像。

返回值

此函式的返回型別為 Image。

示例

示例 1

這是一個使用 ImageChops.logical_and() 函式對由 NumPy 陣列建立的兩個二進位制影像執行邏輯與運算的示例。

from PIL import Image, ImageChops
import numpy as np

# Create two binary images with mode "1"
array1 = np.array([(255, 64, 3), (255, 0, 0), (255, 255, 0), (255, 255, 255), (164, 0, 3)], dtype=np.uint8)
array2 = np.array([(200, 14, 3), (25, 222, 0), (255, 155, 0), (255, 55, 100), (180, 0, 78)], dtype=np.uint8)

image1 = Image.fromarray(array1, mode="1")
image2 = Image.fromarray(array2, mode="1")

# Display the pixel values of the two input images
print("Pixel values of image1 at (0, 0):", image1.getpixel((0, 0)))
print("Pixel values of image2 at (0, 0):", image2.getpixel((0, 0)))

# Perform logical AND between the two images
result = ImageChops.logical_and(image1, image2)

# Display the pixel values of the resulting image at (0, 0)
print("Pixel values of the result at (0, 0) after logical AND:", result.getpixel((0, 0)))

輸出

Pixel values of image1 at (0, 0): 255
Pixel values of image2 at (0, 0): 255
Pixel values of the result at (0, 0) after logical AND: 255

示例 2

在此示例中,PIL.ImageChops.logical_and() 函式用於對兩個二進位制影像(image1 和 image2)執行邏輯與運算。

from PIL import Image, ImageChops

# Create two binary images with mode "1"
image1 = Image.open('Images/dark_img1.png').convert('1')
image2 = Image.open('Images/dark_img2.png').convert('1')

# Perform logical AND between the two images
result = ImageChops.logical_and(image1, image2)

# Display the input and resulting images
image1.show()
image2.show()
result.show()

輸出

輸入影像 1

dark img1

輸入影像 2

dark img2

輸出影像

imagechops logical and

示例 3

這是另一個演示 logical_and() 函式工作的示例。

from PIL import Image, ImageChops

# Create two binary images with mode "1"
image1 = Image.open('Images/Car_2.jpg').convert('1')
image2 = Image.open('Images/ColorDots.png').convert('1')

# Perform logical AND between the two images
result = ImageChops.logical_and(image1, image2)

# Display the input and resulting images
image1.show()
image2.show()
result.show()

輸出

輸入影像 1

car bw

輸入影像 2

dots bw

輸出影像

dotted car
python_pillow_function_reference.htm
廣告