반응형
반응형

입력된 웹 페이지 내에서 모든 <img> 요소를 추출하는 프로그램을 **requests**와 BeautifulSoup 라이브러리를 사용하여 구현해 드리겠습니다. 🔎

이 방법은 웹 크롤링(Web Crawling)의 가장 기본적인 형태이며, HTML을 파싱(Parsing)하여 원하는 특정 태그를 쉽게 찾아낼 수 있습니다.

 

_image_resource_extract.py

 

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import sys

def extract_images_from_url(url):
    """
    주어진 URL의 웹 페이지에서 모든 <img> 태그의 src 속성을 추출합니다.
    
    :param url: 분석할 웹 페이지의 URL
    :return: 이미지 URL 리스트
    """
    if not (url.startswith('http://') or url.startswith('https://')):
        # 사용자가 프로토콜을 생략했을 경우 https://를 기본으로 추가
        url = 'https://' + url
        
    image_list = []
    
    print(f"URL에 접속 중: {url}")
    
    try:
        # 1. HTTP 요청 보내기
        # User-Agent를 설정하여 봇 접근이 아님을 알리고 접속 거부를 방지합니다.
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status() # HTTP 오류가 발생하면 예외 발생
        
        # 2. HTML 파싱 (BeautifulSoup 사용)
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 3. 모든 <img> 태그 찾기
        img_tags = soup.find_all('img')
        
        # 4. 각 태그에서 src 속성 추출
        for img in img_tags:
            src = img.get('src')
            if src:
                # 5. 상대 경로를 절대 경로로 변환
                # <img src="/images/logo.png">와 같은 상대 경로를 처리하기 위해 필요합니다.
                absolute_url = urljoin(url, src)
                image_list.append(absolute_url)
                
    except requests.exceptions.RequestException as e:
        print(f"\n[오류] 웹 페이지에 접속할 수 없습니다: {e}")
        return None
    except Exception as e:
        print(f"\n[오류] 예상치 못한 오류가 발생했습니다: {e}")
        return None
        
    return image_list

if __name__ == "__main__":
    
    # 1. 사용자로부터 URL 입력 받기
    target_url = input("이미지 리스트를 추출할 웹 페이지 URL을 입력하세요 (예: google.com): ").strip()
    
    if not target_url:
        print("URL이 입력되지 않았습니다. 프로그램을 종료합니다.")
        sys.exit()

    # 2. 이미지 추출 실행
    images = extract_images_from_url(target_url)

    # 3. 결과 출력
    print("\n" + "="*50)
    
    if images is not None:
        print(f"📌 발견된 이미지 요소 개수: {len(images)}개")
        print("--- 추출된 이미지 URL 리스트 ---")
        
        # 최대 10개만 출력 (너무 길어지는 것을 방지)
        for i, img_url in enumerate(images[:10]):
            print(f"{i+1}. {img_url}")

        if len(images) > 10:
            print(f"...\n(총 {len(images)}개의 이미지 URL이 발견되었습니다.)")
    
    print("="*50)
반응형
반응형

 

이미지 읽어서 스케치 형식으로 변환

# 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}")

반응형
반응형

[python] SVG to PNG, install cairosvg

 

pip install cairosvg

 

 

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("✅ 모든 변환이 완료되었습니다!")

📂 폴더 구조 예시

🏆 설명

  1. img 폴더 안의 모든 .svg 파일을 찾음.
  2. 각 .svg 파일을 .png로 변환하여 output_png 폴더에 저장.
  3. 변환이 완료되면 메시지를 출력.

✅ 이 코드를 실행하면 img 폴더 안의 모든 SVG 파일이 output_png 폴더에 PNG로 변환되어 저장됩니다! 🚀

반응형
반응형

[python] 폴더 안의 .webp 이미지를 .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)

코드 설명

  1. Pillow 라이브러리 사용: Pillow의 Image 모듈을 사용하여 이미지를 열고 변환합니다.
  2. 폴더 내 파일 탐색:
    • os.listdir(folder_path)를 사용하여 지정된 폴더 내의 모든 파일을 가져옵니다.
    • if filename.endswith(".webp"): 조건문을 사용하여 .webp 확장자를 가진 파일만 필터링합니다.
  3. 파일 경로 생성:
    • webp_file_path는 원본 .webp 파일의 전체 경로입니다.
    • png_filename은 .webp 확장자를 .png로 대체한 새 파일 이름입니다.
    • png_file_path는 변환된 .png 파일의 전체 경로입니다.
  4. 이미지 변환 및 저장:
    • Image.open(webp_file_path)를 사용하여 .webp 파일을 열고, img.save(png_file_path, "png")를 사용하여 .png 파일로 저장합니다.
  5. 사용 방법:
    • folder_path 변수에 변환할 .webp 파일이 있는 폴더 경로를 입력합니다.
    • 프로그램을 실행하면 폴더 내 모든 .webp 파일이 .png 파일로 변환됩니다.

사용 예시

예를 들어, 폴더 경로가 C:/Users/YourName/Documents/Images인 경우:

folder_path = 'C:/Users/YourName/Documents/Images'
convert_webp_to_png(folder_path)

위 코드를 실행하면 해당 폴더 내의 모든 .webp 파일이 .png 형식으로 변환됩니다.

반응형
반응형

[python] PyMuPDF 에서 해상도 올리기. PDF to IMG

How to Increase Image Resolution

 

https://pymupdf.readthedocs.io/en/latest/recipes-images.html

 

Images - PyMuPDF 1.23.25 documentation

Previous Text

pymupdf.readthedocs.io

The image of a document page is represented by a Pixmap, and the simplest way to create a pixmap is via method Page.get_pixmap().

This method has many options to influence the result. The most important among them is the Matrix, which lets you zoom, rotate, distort or mirror the outcome.

Page.get_pixmap() by default will use the Identity matrix, which does nothing.

In the following, we apply a zoom 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 specify pix = page.get_pixmap(dpi=300). Apart from notation brevity, this approach has the additional advantage that the dpi value is saved with the image file – 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)

[python] 이미지에서 텍스트 추출하기,  tesseract, OCR

 

 

반응형

+ Recent posts