0

Unable to resize image using cv2 after converting pdf to images using pdf2image package.

The code is

import os
import cv2
from pdf2image import convert_from_path
pdf_files = [filename for filename in os.listdir(
    os.getcwd()) if filename.endswith('.pdf')]
for pdf_file in pdf_files:
    images = convert_from_path(pdf_file, 400)
    for i, image in enumerate(images):
        fname = pdf_file+'_image'+str(i)+'.jpg'
        fname = cv2.resize(fname, (3400, 4400))
        image.save(fname, "JPEG")

Error is

fname = cv2.resize(fname, (3400, 4400))
TypeError: Expected Ptr<cv::UMat> for argument 'src'
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Nithin Reddy
  • 580
  • 2
  • 8
  • 18

1 Answers1

0

You're trying to resize your filename in this line of your code:

fname = cv2.resize(fname, (3400, 4400))

Replace the above line with:

image = cv2.resize(image, (3400, 4400))

To save the image the command will be cv2.imwrite(fname, image)

Also you would need to convert your images to arrays. For that, you have to import numpy. Here is the complete code:

import os
import cv2
import numpy as np 
from pdf2image import convert_from_path
pdf_files = [filename for filename in os.listdir(
    os.getcwd()) if filename.endswith('.pdf')]
for pdf_file in pdf_files:
    images = convert_from_path(pdf_file, 400)
    for i, image in enumerate(images):
        fname = pdf_file+'_image'+str(i)+'.jpg'
        image = np.array(image)
        image = cv2.resize(image, (3400, 4400))
        cv2.imwrite(fname, image)
kindustrii
  • 369
  • 1
  • 8
  • I've updated my answer. Does this work for you? – kindustrii Feb 17 '21 at 06:41
  • It worked, but the yellow color in pdf is blue in converted image. Is there any mistake? – Nithin Reddy Feb 17 '21 at 07:28
  • `cv2.imwrite(fname, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))` should fix it. You can find more details [here](https://stackoverflow.com/questions/42406338/why-cv2-imwrite-changes-the-color-of-pics) – kindustrii Feb 17 '21 at 08:02