You can concatenate two cropped parts of an image using PIL (Python Imaging Library) in Python by using the paste() method. Here's a step-by-step guide:
Prerequisites
- Install PIL using pip:
pip install pillow
Code
from PIL import Image
# Open the original image
img = Image.open('original_image.jpg')
# Crop the first part of the image
cropped_img1 = img.crop((0, 0, 100, 100)) # Crop from (left, top, right, bottom)
# Crop the second part of the image
cropped_img2 = img.crop((150, 0, 250, 100)) # Crop from (left, top, right, bottom)
# Create a new image with the combined width
combined_img = Image.new('RGB', (cropped_img1.width + cropped_img2.width, cropped_img1.height))
# Paste the cropped images into the new image
combined_img.paste(cropped_img1, (0, 0))
combined_img.paste(cropped_img2, (cropped_img1.width, 0))
# Save the combined image
combined_img.save('combined_image.jpg')
Explanation
- Open the original image using
Image.open().
- Crop the desired parts of the image using
img.crop(). The crop() method takes a tuple of four values: (left, top, right, bottom), which define the region of interest.
- Create a new image with the combined width of the two cropped parts using
Image.new(). The mode is set to 'RGB' for color images.
- Paste the cropped images into the new image using
paste(). The first argument is the image to paste, and the second argument is the position (x, y) where the image should be pasted.
- Save the combined image using
save().
Example Use Case
Suppose you have an image with a width of 500 pixels and you want to concatenate two cropped parts:
- Part 1:
(0, 0, 200, 100) (left, top, right, bottom)
- Part 2:
(300, 0, 500, 100) (left, top, right, bottom)
The code above will create a new image with a width of 400 pixels (200 + 200) and a height of 100 pixels.
Tips
- Make sure the cropped parts have the same height to ensure a seamless concatenation.
- You can adjust the position of the pasted images by changing the
(x, y) coordinates in the paste() method.
- If you want to concatenate more than two images, simply repeat the
paste() method with the updated position.