How to Crop Image using Pyhton and Save the Result in Another Folder?

Viewed 65

I have a function to crop image using python. Right now it will process the image 1 by 1, however, I want to crop all images in 1 folder. I need to modify the function to be able process all images in 1 folder and save the result in excel.

def send_request_croppingsegm(file_path, doctype):
url = 'http://52.77.70.50:8006/detectGeneralDocumentV3/single'
files=[ ('imageFile', (file_path.split('/')[-1], open(file_path, 'rb'), 'image/png')) ]
headers = {}
payload = {'documentType': doctype}
res = requests.request("POST", url, data=payload, files=files, verify=verify).text
res = json.loads(res)
cropped_data64 = base64.b64decode(res['document_image'])
cropped_img = Image.open(io.BytesIO(cropped_data64))    
return cropped_img

DEFAULT_DIR = 'C:/Users/API Test'

fn = 'ucf.png'
imgpath = os.path.join(DEFAULT_DIR, fn)
cropped = send_request_croppingsegm(imgpath, 2)
plt.imshow(cropped)
1 Answers
import os
# list all files in directory
for i in os.listdir(DEFAULT_DIR):
  # if it ends with '.png'
  if i.endswith(".png"):
    imgpath = os.path.join(DEFAULT_DIR, i)
    cropped = send_request_croppingsegm(imgpath, 2)
    plt.imshow(cropped)
Related