Image Preprocessing#

Dataset source: https://sipi.usc.edu/database/database.php?volume=misc

!poetry add opencv-python
The following packages are already present in the pyproject.toml and will be skipped:

  - opencv-python

If you want to update it to the latest compatible version, you can use `poetry update package`.
If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.

Nothing to add.
from matplotlib import pyplot as plt


def display_cv2_image(img):
    plt.imshow(img, cmap="gray")
    plt.show()

Loading and converting images#

import cv2

img = cv2.imread("../../data/peppers.tiff")
display_cv2_image(img)
../_images/d34f3a0987a0590da6f5bb3388d3847aa8f0618eff3ac4af353384581dcae905.png

Converting between color spaces#

rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
display_cv2_image(rgb_img)
../_images/3345e80c949e7328c3f11d919a6ecdb516f97bd414374292a7b794ed7887dee7.png
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
display_cv2_image(gray_img)
../_images/5dd80991689a718c9f9f933c07a187d30ed4d7aa8a40ceb735e4e4d9fce7114a.png

Resizing and cropping images#

resized = cv2.resize(rgb_img, (100, 100))
display_cv2_image(resized)
../_images/41b5e507ed3c6a0d1414387cd20b2ea8cb7af828c3c9dcddb47eaff86b44b000.png
x1, y1 = 100, 100  # Top-left corner
x2, y2 = 400, 400  # Bottom-right corner

cropped = rgb_img[y1:y2, x1:x2]
display_cv2_image(cropped)
../_images/18b9e8c7851422c875e05c389b3337d906c60050db3076150b3217e0192c5008.png