62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
# write a pytohn code that will read a image named `helloworld.jpg`,
|
|
# crop 20x20 pixels randomly
|
|
# create a output folder named `output`,
|
|
# save the cropped image in the output folder, and rename it to `helloworld_cropped.jpg`
|
|
import os,sys
|
|
import cv2
|
|
import random
|
|
|
|
crop_width = int(sys.argv[1])
|
|
crop_height = int(sys.argv[2])
|
|
no_files = int(sys.argv[3])
|
|
no_slices = int(sys.argv[4])
|
|
|
|
# remove all files in output before start
|
|
for file in os.listdir('output'):
|
|
file_path = os.path.join('output', file)
|
|
try:
|
|
if os.path.isfile(file_path):
|
|
os.unlink(file_path)
|
|
except Exception as e:
|
|
print(e)
|
|
|
|
# Read the image
|
|
images = []
|
|
for i in range(100, 199+1):
|
|
image = cv2.imread(f'_pool/{i}.jpg')
|
|
images.append(image)
|
|
|
|
j = 0
|
|
for _ in range(no_files):
|
|
# Randomly select a image from images
|
|
image = random.choice(images)
|
|
if image is None:
|
|
continue
|
|
height, width, _ = image.shape
|
|
|
|
# Generate random coordinates for cropping
|
|
|
|
x = random.randint(0, width - crop_width)
|
|
y = random.randint(0, height - crop_height)
|
|
|
|
# Crop the image
|
|
cropped_image = image[y:y+crop_height, x:x+crop_width]
|
|
|
|
for i in range(no_slices):
|
|
j+=1
|
|
# Generate random coordinates for cropping
|
|
x = random.randint(0, width - crop_width)
|
|
y = random.randint(0, height - crop_height)
|
|
|
|
# Crop the image
|
|
cropped_image = image[y:y+crop_height, x:x+crop_width]
|
|
|
|
# Create output directory if it doesn't exist
|
|
output_dir = 'output'
|
|
if not os.path.exists(output_dir):
|
|
os.makedirs(output_dir)
|
|
|
|
# Save the cropped image
|
|
cv2.imwrite(os.path.join(output_dir, 'beach_{}.jpg'.format(j)), cropped_image)
|
|
|