要避免从PDF中提取重复的图片,可以使用以下解决方法:
import cv2
import imagehash
def extract_image_hashes(pdf_file):
image_hashes = []
with pdfplumber.open(pdf_file) as pdf:
for page in pdf.pages:
for image in page.images:
img = image.to_image()
img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
img_hash = imagehash.phash(Image.fromarray(img_cv2))
image_hashes.append(img_hash)
return image_hashes
def remove_duplicate_images(pdf_file):
image_hashes = extract_image_hashes(pdf_file)
unique_image_hashes = list(set(image_hashes))
with pdfplumber.open(pdf_file) as pdf:
for page in pdf.pages:
for image in page.images:
img = image.to_image()
img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
img_hash = imagehash.phash(Image.fromarray(img_cv2))
if img_hash in unique_image_hashes:
unique_image_hashes.remove(img_hash)
else:
# save the unique image or perform some other action
import cv2
import numpy as np
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.models import Model
def extract_image_features(pdf_file):
image_features = []
base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
with pdfplumber.open(pdf_file) as pdf:
for page in pdf.pages:
for image in page.images:
img = image.to_image()
img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
img_resized = cv2.resize(img_cv2, (224, 224))
img_preprocessed = preprocess_input(np.expand_dims(img_resized, axis=0))
img_feature = model.predict(img_preprocessed)[0]
image_features.append(img_feature)
return image_features
def remove_duplicate_images(pdf_file):
image_features = extract_image_features(pdf_file)
unique_image_features = []
with pdfplumber.open(pdf_file) as pdf:
for page in pdf.pages:
for image in page.images:
img = image.to_image()
img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
img_resized = cv2.resize(img_cv2, (224, 224))
img_preprocessed = preprocess_input(np.expand_dims(img_resized, axis=0))
img_feature = model.predict(img_preprocessed)[0]
if not any(np.allclose(img_feature, feat) for feat in unique_image_features):
unique_image_features.append(img_feature)
else:
# save the unique image or perform some other action
这些示例代码使用了Python的pdfplumber库来从PDF中提取图片,并使用了OpenCV和PIL库来处理图像。第一个示例使用了图像哈希算法来进行判断,而第二个示例使用了深度学习模型来提取图像的特征向量。根据具体情况选择适合的方法。
上一篇:避免从模块中调用私有方法