# img_to_sketch_001.py
# 이미지 읽어서 스케치 형식으로 변환
# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다.
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)
import cv2
import numpy as np
import os
def convert_to_sketch(image_path, output_path="sketch_output.jpg"):
"""
사진을 읽어들여 스케치 형식으로 변환하고 저장합니다.
"""
try:
# 1. 이미지 로드
img = cv2.imread(image_path)
if img is None:
print(f"오류: 이미지를 로드할 수 없습니다. 경로를 확인하세요: {image_path}")
return
# 2. 이미지를 회색조로 변환
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 3. 이미지 반전 (어두운 부분은 밝게, 밝은 부분은 어둡게)
# 펜으로 그린 선처럼 보이게 합니다.
inverted_img = 255 - gray_img
# 4. 가우시안 블러 적용
# 이미지를 부드럽게 만들고, 반전된 이미지와 블렌딩할 때 경계를 부드럽게 합니다.
# (21, 21)은 커널 크기, 0은 시그마 값 (자동 계산)
blurred_img = cv2.GaussianBlur(inverted_img, (21, 21), 0)
# 5. 컬러 닷지 블렌드 모드 적용 (스케치 효과의 핵심)
# 원본 회색조 이미지와 블러 처리된 반전 이미지를 혼합합니다.
# "닷지(Dodge)" 모드는 밝은 영역을 더 밝게 만들고, 어두운 영역의 디테일을 유지합니다.
# OpenCV에서는 직접적인 닷지 블렌드 모드 함수를 제공하지 않으므로, 수학적 연산을 사용합니다.
# result = (gray_img * 256) / (255 - blurred_img + epsilon)
# 여기서 255 - blurred_img가 0이 되는 것을 방지하기 위해 작은 값(epsilon)을 더합니다.
epsilon = 10 # 0으로 나누는 것을 방지하기 위한 작은 상수
sketch_img = cv2.divide(gray_img, 255 - blurred_img + epsilon, scale=256)
# 6. 결과 이미지 저장
cv2.imwrite(output_path, sketch_img)
print(f"스케치 이미지가 '{output_path}'로 성공적으로 저장되었습니다.")
except Exception as e:
print(f"스케치 변환 중 오류 발생: {e}")
# --- 사용 예시 ---
# 1. 'input_image.jpg' 라는 이름의 사진 파일을 이 파이썬 스크립트와 같은 폴더에 놓으세요.
# 2. 또는 정확한 이미지 파일 경로를 지정하세요.
input_image_path = "person_01.jpg"
# 파일명과 확장자 분리 및 새 파일명 생성
file_name_without_extension, file_extension = os.path.splitext(input_image_path)
output_sketch_path = f"{file_name_without_extension}_sketch{file_extension}"
print(f"원본 파일명: {input_image_path}")
print(f"확장자 없는 파일명: {file_name_without_extension}")
print(f"확장자: {file_extension}")
#output_caricature_path = file_name_without_extension + "_caricature_result." + file_extension
# F-string을 사용하여 문자열 내부에 변수를 직접 삽입합니다.
output_sketch_path = f"{file_name_without_extension}_caricature_result{file_extension}"
convert_to_sketch(input_image_path, output_sketch_path)
# 결과 이미지 확인 (선택 사항)
# try:
# # OpenCV로 이미지 표시 (OpenCV 창을 사용)
# result_img = cv2.imread(output_sketch_path)
# if result_img is not None:
# cv2.imshow("Sketch Image", result_img)
# cv2.waitKey(0) # 아무 키나 누를 때까지 대기
# cv2.destroyAllWindows() # 모든 OpenCV 창 닫기
# else:
# print("결과 이미지를 읽을 수 없습니다.")
# except FileNotFoundError:
# print("결과 이미지를 찾을 수 없어 미리보기를 실행할 수 없습니다.")
# except Exception as e:
# print(f"결과 이미지 미리보기 중 오류 발생: {e}")
import os
import cairosvg
# 변환할 폴더 경로
input_folder = "img"
output_folder = "output_png"
# 출력 폴더가 없으면 생성
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# img 폴더 안의 모든 SVG 파일 변환
for filename in os.listdir(input_folder):
if filename.lower().endswith(".svg"): # 확장자가 .svg인 파일만 처리
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename.replace(".svg", ".png"))
# SVG → PNG 변환
cairosvg.svg2png(url=input_path, write_to=output_path)
print(f"변환 완료: {filename} → {output_path}")
print("✅ 모든 변환이 완료되었습니다!")
📂 폴더 구조 예시
🏆 설명
img 폴더 안의 모든 .svg 파일을 찾음.
각 .svg 파일을 .png로 변환하여 output_png 폴더에 저장.
변환이 완료되면 메시지를 출력.
✅ 이 코드를 실행하면 img 폴더 안의 모든 SVG 파일이 output_png 폴더에 PNG로 변환되어 저장됩니다! 🚀
.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
def convert_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 2 in 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 files
for 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 string
print(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 error
print(pytesseract.image_to_string('test.png'))
# List of available languages
print(pytesseract.get_languages(config=''))
# French text image to string
print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra'))
# Batch processing with a single file containing the list of multiple image file paths
print(pytesseract.image_to_string('images.txt'))
# Timeout/terminate the tesseract job after a period of time
try:
print(pytesseract.image_to_string('test.jpg', timeout=2)) # Timeout after 2 seconds
print(pytesseract.image_to_string('test.jpg', timeout=0.5)) # Timeout after half a second
except RuntimeError as timeout_error:
# Tesseract processing is terminated
pass
# Get bounding box estimates
print(pytesseract.image_to_boxes(Image.open('test.png')))
# Get verbose data including boxes, confidences, line and page numbers
print(pytesseract.image_to_data(Image.open('test.png')))
# Get information about orientation and script detection
print(pytesseract.image_to_osd(Image.open('test.png')))
# Get a searchable PDF
pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf')
with open('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.