How can I crop images, like I\'ve done before in PIL, using OpenCV.
Working example on PIL
im = Image.open(\'0.png\').convert(\'L\')
im = im.crop((1
Alternatively, you could use tensorflow for the cropping and openCV for making an array from the image.
import cv2
img = cv2.imread('YOURIMAGE.png')
Now img is a (imageheight, imagewidth, 3) shape array. Crop the array with tensorflow:
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
Reassemble the image with tf.keras, so we can look at it if it worked:
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)
This prints out the pic in a notebook (tested in Google Colab).
The whole code together:
import cv2
img = cv2.imread('YOURIMAGE.png')
import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
img, offset_height, offset_width, target_height, target_width
)
tf.keras.preprocessing.image.array_to_img(
x, data_format=None, scale=True, dtype=None
)