.webp 이미지를 .png로 변환하는 Python 프로그램을 작성할 수 있습니다. 이를 위해 Pillow 라이브러리를 사용합니다. Pillow는 Python의 이미지 처리 라이브러리로, 다양한 이미지 형식을 다룰 수 있습니다.
다음은 특정 폴더 내의 모든 .webp 이미지를 .png로 변환하는 프로그램입니다:
1. Pillow 설치
먼저 Pillow 라이브러리를 설치해야 합니다. 터미널이나 명령 프롬프트에서 다음 명령어를 실행하세요:
pip install Pillow
2. .webp 이미지를 .png로 변환하는 코드
아래 코드 예시는 지정된 폴더 내의 모든 .webp 파일을 .png 파일로 변환합니다:
from PIL import Image
import os
defconvert_webp_to_png(folder_path):# 폴더 내 모든 파일을 반복for filename in os.listdir(folder_path):
if filename.endswith(".webp"):
# 파일의 전체 경로 생성
webp_file_path = os.path.join(folder_path, filename)
# .webp 파일을 열고 .png로 저장
png_filename = filename[:-5] + ".png"# 파일 확장자를 .png로 변경
png_file_path = os.path.join(folder_path, png_filename)
with Image.open(webp_file_path) as img:
img.save(png_file_path, "png")
print(f"Converted: '{filename}' -> '{png_filename}'")
# 사용 예시
folder_path = 'path_to_your_folder'# 여기에 폴더 경로를 입력하세요
convert_webp_to_png(folder_path)
코드 설명
Pillow 라이브러리 사용: Pillow의 Image 모듈을 사용하여 이미지를 열고 변환합니다.
폴더 내 파일 탐색:
os.listdir(folder_path)를 사용하여 지정된 폴더 내의 모든 파일을 가져옵니다.
if filename.endswith(".webp"): 조건문을 사용하여 .webp 확장자를 가진 파일만 필터링합니다.
파일 경로 생성:
webp_file_path는 원본 .webp 파일의 전체 경로입니다.
png_filename은 .webp 확장자를 .png로 대체한 새 파일 이름입니다.
png_file_path는 변환된 .png 파일의 전체 경로입니다.
이미지 변환 및 저장:
Image.open(webp_file_path)를 사용하여 .webp 파일을 열고, img.save(png_file_path, "png")를 사용하여 .png 파일로 저장합니다.
사용 방법:
folder_path 변수에 변환할 .webp 파일이 있는 폴더 경로를 입력합니다.
프로그램을 실행하면 폴더 내 모든 .webp 파일이 .png 파일로 변환됩니다.
사용 예시
예를 들어, 폴더 경로가 C:/Users/YourName/Documents/Images인 경우:
The image of a document page is represented by aPixmap, and the simplest way to create a pixmap is via methodPage.get_pixmap().
This method has many options to influence the result. The most important among them is theMatrix, which lets youzoom, rotate, distort or mirror the outcome.
In the following, we apply azoom factor of 2 to each dimension, which will generate an image with a four times better resolution for us (and also about 4 times the size):
zoom_x = 2.0 # horizontal zoom
zoom_y = 2.0 # vertical zoom
mat = fitz.Matrix(zoom_x, zoom_y) # zoom factor 2in each dimension
pix = page.get_pixmap(matrix=mat) # use 'mat' instead of the identity matrix
dpi = 600
pix = page.get_pixmap(dpi)
Since version 1.19.2 there is a more direct way to set the resolution: Parameter"dpi"(dots per inch) can be used in place of"matrix". To create a 300 dpi image of a page specifypix=page.get_pixmap(dpi=300). Apart from notation brevity, this approach has the additional advantage that thedpi value is saved with the imagefile – which does not happen automatically when using the Matrix notation.
# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다. import os
from pathlib import Path
# src 상위 폴더를 실행폴더로 지정하려고 한다.###real_path = Path(__file__).parent.parent
real_path = Path(__file__).parent
print(real_path)
#작업 디렉토리 변경
os.chdir(real_path)
"""_summary_
pip install pillow
pip install pytesseract
다운 받아야하는 학습된 한글 데이터 파일명: kor.traineddata
파일 위치: tesseract가 설치된 경로 C:\Program Files\Tesseract-OCR\tessdata
"""from PIL import Image
import pytesseract
import cv2
import matplotlib.pyplot as plt
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
config = ('-l kor+eng --oem 3 --psm 11')
#config = ('-l kor+eng')
directory_base = str(real_path)+"./img/"# 경로object를 문자열로 변경해서 합친다. # Open an image file
image_path = directory_base+"03_kor_eng.png"# Replace with your image file path
img = Image.open(image_path)
# Use Tesseract to extract text
text = pytesseract.image_to_string(img, config=config)
print("Extracted Text:" + text)
image = cv2.imread(image_path)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(rgb_image)
# use Tesseract to OCR the image # text = pytesseract.image_to_string(rgb_image, lang='kor+eng')
text = pytesseract.image_to_string(rgb_image, config=config)
print(text)
if __name__ == "__main__":
# List all files in the directory
file_list = [f for f in os.listdir(directory_base) if os.path.isfile(os.path.join(directory_base, f))]
# Print the list of filesfor file in file_list:
print(file)
# Open an image file
image_path = directory_base + file # Replace with your image file path
img = Image.open(image_path)
text = pytesseract.image_to_string(img, config=config)
print("Extracted Text:")
print(text)
다운 받아야하는 학습된 한글 데이터 파일명:kor.traineddata 파일 위치: tesseract가 설치된 경로C:\Program Files\Tesseract-OCR\tessdata
*** 설치 할때 언어팩 선택
pytesseract 0.3.10
Python-tesseract is an optical character recognition (OCR) tool for python. That is, it will recognize and “read” the text embedded in images.
Python-tesseract is a wrapper forGoogle’s Tesseract-OCR Engine. It is also useful as a stand-alone invocation script to tesseract, as it can read all image types supported by the Pillow and Leptonica imaging libraries, including jpeg, png, gif, bmp, tiff, and others. Additionally, if used as a script, Python-tesseract will print the recognized text instead of writing it to a file.
USAGE
Quickstart
Note: Test images are located in thetests/datafolder of the Git repo.
Library usage:
from PIL import Image
import pytesseract
# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'# Simple image to stringprint(pytesseract.image_to_string(Image.open('test.png')))
# In order to bypass the image conversions of pytesseract, just use relative or absolute image path# NOTE: In this case you should provide tesseract supported images or tesseract will return errorprint(pytesseract.image_to_string('test.png'))
# List of available languagesprint(pytesseract.get_languages(config=''))
# French text image to stringprint(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
# Batch processing with a single file containing the list of multiple image file pathsprint(pytesseract.image_to_string('images.txt'))
# Timeout/terminate the tesseract job after a period of timetry:
print(pytesseract.image_to_string('test.jpg', timeout=2)) # Timeout after 2 secondsprint(pytesseract.image_to_string('test.jpg', timeout=0.5)) # Timeout after half a secondexcept RuntimeError as timeout_error:
# Tesseract processing is terminatedpass# Get bounding box estimatesprint(pytesseract.image_to_boxes(Image.open('test.png')))
# Get verbose data including boxes, confidences, line and page numbersprint(pytesseract.image_to_data(Image.open('test.png')))
# Get information about orientation and script detectionprint(pytesseract.image_to_osd(Image.open('test.png')))
# Get a searchable PDF
pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf')
withopen('test.pdf', 'w+b') as f:
f.write(pdf) # pdf type is bytes by default# Get HOCR output
hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr')
# Get ALTO XML output
xml = pytesseract.image_to_alto_xml('test.png')
Support for OpenCV image/NumPy array objects
import cv2
img_cv = cv2.imread(r'/<path_to_image>/digits.png')
# By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,# we need to convert from BGR to RGB format/mode:
img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
print(pytesseract.image_to_string(img_rgb))
# OR
img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0)
print(pytesseract.image_to_string(img_rgb))
If you need custom configuration likeoem/psm, use theconfigkeyword.
# Example of adding any additional options
custom_oem_psm_config = r'--oem 3 --psm 6'
pytesseract.image_to_string(image, config=custom_oem_psm_config)
# Example of using pre-defined tesseract config file with options
cfg_filename = 'words'
pytesseract.run_and_get_output(image, extension='txt', config=cfg_filename)
Add the following config, if you have tessdata error like: “Error opening data file…”
# Example config: r'--tessdata-dir "C:\Program Files (x86)\Tesseract-OCR\tessdata"'# It's important to add double quotes around the dir path.
tessdata_dir_config = r'--tessdata-dir "<replace_with_your_tessdata_dir_path>"'
pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config)
Functions
get_languagesReturns all currently supported languages by Tesseract OCR.
get_tesseract_versionReturns the Tesseract version installed in the system.
image_to_stringReturns unmodified output as string from Tesseract OCR processing
image_to_boxesReturns result containing recognized characters and their box boundaries
image_to_dataReturns result containing box boundaries, confidences, and other information. Requires Tesseract 3.05+. For more information, please check theTesseract TSV documentation
image_to_osdReturns result containing information about orientation and script detection.
image_to_alto_xmlReturns result in the form of Tesseract’s ALTO XML format.
run_and_get_outputReturns the raw output from Tesseract OCR. Gives a bit more control over the parameters that are sent to tesseract.
imageObject or String - PIL Image/NumPy array or file path of the image to be processed by Tesseract. If you pass object instead of file path, pytesseract will implicitly convert the image toRGB mode.
langString - Tesseract language code string. Defaults toengif not specified! Example for multiple languages:lang='eng+fra'
configString - Anyadditional custom configuration flagsthat are not available via the pytesseract function. For example:config='--psm6'
niceInteger - modifies the processor priority for the Tesseract run. Not supported on Windows. Nice adjusts the niceness of unix-like processes.
output_typeClass attribute - specifies the type of the output, defaults tostring. For the full list of all supported types, please check the definition ofpytesseract.Outputclass.
timeoutInteger or Float - duration in seconds for the OCR processing, after which, pytesseract will terminate and raise RuntimeError.
pandas_configDict - only for theOutput.DATAFRAMEtype. Dictionary with custom arguments forpandas.read_csv. Allows you to customize the output ofimage_to_data.
CLI usage:
pytesseract [-l lang] image_file
INSTALLATION
Prerequisites:
Python-tesseract requires Python 3.6+
You will need the Python Imaging Library (PIL) (or thePillowfork). Under Debian/Ubuntu, this is the packagepython-imagingorpython3-imaging.
InstallGoogle Tesseract OCR(additional info how to install the engine on Linux, Mac OSX and Windows). You must be able to invoke the tesseract command astesseract. If this isn’t the case, for example because tesseract isn’t in your PATH, you will have to change the “tesseract_cmd” variablepytesseract.pytesseract.tesseract_cmd. Under Debian/Ubuntu you can use the packagetesseract-ocr. For Mac OS users. please install homebrew packagetesseract.
Note:In some rare cases, you might need to additionally installtessconfigsandconfigsfromtesseract-ocr/tessconfigsif the OS specific package doesn’t include them.
// `response` is an instance of System.Net.Http.HttpResponseMessage
response.Headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
response.Headers.Pragma.ParseAdd("no-cache");
// We can't use `response.Content.Headers.Expires` directly// since it allows only `DateTimeOffset?` values.
response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString());