Home > front end >  cv.imwrite does not want to write a PIL Image
cv.imwrite does not want to write a PIL Image

Time:09-14

I have a function to crop images and I need to save the result to another folder. However I got error. I need help to save all the results to another folder and also shows all the cropped images using plt.imshow(cropped)

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/Desktop/API Test'
TARGET_DIRECTORY = 'C:/Users/Desktop/Crop'

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)
    cv2.imwrite(os.path.join(TARGET_DIRECTORY, i), cropped)

Error message:

enter image description here

CodePudding user response:

You have to convert cropped to a numpy array before saving. Try:

import numpy as np
cv2.imwrite(os.path.join(TARGET_DIRECTORY, i), np.asarray(cropped))
  • Related