반응형

[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

 

 

반응형
반응형

pip install pytesseract

 

한글팩 : https://github.com/tesseract-ocr/tessdata/

 
다운 받아야하는 학습된 한글 데이터 파일명: 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 for Google’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 the tests/data folder 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 like oem/psm, use the config keyword.

# 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_languages Returns all currently supported languages by Tesseract OCR.
  • get_tesseract_version Returns the Tesseract version installed in the system.
  • image_to_string Returns unmodified output as string from Tesseract OCR processing
  • image_to_boxes Returns result containing recognized characters and their box boundaries
  • image_to_data Returns result containing box boundaries, confidences, and other information. Requires Tesseract 3.05+. For more information, please check the Tesseract TSV documentation
  • image_to_osd Returns result containing information about orientation and script detection.
  • image_to_alto_xml Returns result in the form of Tesseract’s ALTO XML format.
  • run_and_get_output Returns the raw output from Tesseract OCR. Gives a bit more control over the parameters that are sent to tesseract.

Parameters

image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, pandas_config=None)

  • image Object 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 to RGB mode.
  • lang String - Tesseract language code string. Defaults to eng if not specified! Example for multiple languages: lang='eng+fra'
  • config String - Any additional custom configuration flags that are not available via the pytesseract function. For example: config='--psm 6'
  • nice Integer - modifies the processor priority for the Tesseract run. Not supported on Windows. Nice adjusts the niceness of unix-like processes.
  • output_type Class attribute - specifies the type of the output, defaults to string. For the full list of all supported types, please check the definition of pytesseract.Output class.
  • timeout Integer or Float - duration in seconds for the OCR processing, after which, pytesseract will terminate and raise RuntimeError.
  • pandas_config Dict - only for the Output.DATAFRAME type. Dictionary with custom arguments for pandas.read_csv. Allows you to customize the output of image_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 the Pillow fork). Under Debian/Ubuntu, this is the package python-imaging or python3-imaging.
  • Install Google Tesseract OCR (additional info how to install the engine on Linux, Mac OSX and Windows). You must be able to invoke the tesseract command as tesseract. If this isn’t the case, for example because tesseract isn’t in your PATH, you will have to change the “tesseract_cmd” variable pytesseract.pytesseract.tesseract_cmd. Under Debian/Ubuntu you can use the package tesseract-ocr. For Mac OS users. please install homebrew package tesseract.
  • Note: In some rare cases, you might need to additionally install tessconfigs and configs from tesseract-ocr/tessconfigs if the OS specific package doesn’t include them.
Installing via pip:

Check the pytesseract package page for more information.

pip install pytesseract
Or if you have git installed:
pip install -U git+https://github.com/madmaze/pytesseract.git
Installing from source:
git clone https://github.com/madmaze/pytesseract.git
cd pytesseract && pip install -U .
Install with conda (via conda-forge):
conda install -c conda-forge pytesseract

TESTING

To run this project’s test suite, install and run tox. Ensure that you have tesseract installed and in your PATH.

pip install tox
tox

반응형
반응형

How do we control web page caching, across all browsers?

조사 결과 모든 브라우저가 동일한 방식으로 HTTP 캐시 지시문을 준수하는 것은 아닙니다.

보안상의 이유로 우리는 웹 브라우저 에서 애플리케이션의 특정 페이지를 캐시하는 것을 절대 원하지 않습니다 . 이것은 최소한 다음 브라우저에서 작동해야 합니다.

  • 인터넷 익스플로러 6+
  • 파이어폭스 1.5 이상
  • 사파리 3+
  • 오페라 9+
  • 크롬

우리의 요구 사항은 보안 테스트에서 나왔습니다. 당사 웹사이트에서 로그아웃한 후 뒤로 버튼을 눌러 캐시된 페이지를 볼 수 있습니다.

PHP 사용:

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

Java 서블릿 또는 Node.js 사용:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.

ASP.NET-MVC 사용

Response.Cache.SetCacheability(HttpCacheability.NoCache);  // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.

ASP.NET 웹 API 사용:

// `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()); 

ASP.NET 사용:

Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.

ASP.NET Core v3 사용

// using Microsoft.Net.Http.Headers
Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
Response.Headers[HeaderNames.Expires] = "0";
Response.Headers[HeaderNames.Pragma] = "no-cache";

ASP 사용:

Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response.addHeader "Expires", "0" ' Proxies.

Ruby on Rails 사용:

headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
headers["Pragma"] = "no-cache" # HTTP 1.0.
headers["Expires"] = "0" # Proxies.

파이썬/플라스크 사용:

response = make_response(render_template(...))
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response.headers["Pragma"] = "no-cache" # HTTP 1.0.
response.headers["Expires"] = "0" # Proxies.

Python/Django 사용:

response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.

파이썬/피라미드 사용:

request.response.headerlist.extend(
    (
        ('Cache-Control', 'no-cache, no-store, must-revalidate'),
        ('Pragma', 'no-cache'),
        ('Expires', '0')
    )
)

이동 사용:

responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter.Header().Set("Expires", "0") // Proxies.

Clojure 사용(Ring utils 필요):

(require '[ring.util.response :as r])
(-> response
  (r/header "Cache-Control" "no-cache, no-store, must-revalidate")
  (r/header "Pragma" "no-cache")
  (r/header "Expires" 0))

아파치 .htaccess파일 사용:

<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

HTML 사용:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

HTML 메타 태그 대 HTTP 응답 헤더

 

 

https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers

 

How do we control web page caching, across all browsers?

Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner. For security reasons we do not want certain pages in our application to be cached, eve...

stackoverflow.com

 

반응형
반응형

사람에 따라 꿈에 대한 정의나 이미지가 다르겠지만,
저에게 꿈은 목표로 삼아야 하는 것이라기보다는 꼭 되어야 할 모습이에요.
그러니까 목표가 아니라 의무죠. 꿈을 위해 산다는 건 멋진 일이에요.
나답게 자유로운 삶을 살기 위해서는 꿈을 갖는 것이 중요해요.
- 테라오 겐 발뮤다 창업회장, ‘상식의 틀을 깨라’에서


“꿈이 의무가 되는 것이 오히려 마음도 편하고 즐거워요.
이런 의무는 부담스럽게 느껴지지도 않아요.
‘나라면 할 수 있다’라는 전제에 긍정적인 기운이 담겨 있기 때문이죠.
꿈이 단순히 하고 싶은 희망인 경우라면 행동이 좀처럼 따라주지 않을 수도 있지만
꼭 해야만 하는 일이 되면 저절로 행동이 따르게 되거든요.”

반응형
반응형


성공은 당신이 아는 지식 덕분이 아니라,
당신이 아는 사람들과 그들에게 비춰지는
당신의 이미지를 통해 찾아온다.
- 리 아이아코카(Lee Iacocca), 크라이슬러 전 회장

실력배양 없이 네트워킹에만 힘을 쏟는 것도 문제지만,
능력은 갖추고 있으면서 네트워킹을 소홀히 하는 것 또한
바람직한 일은 아닙니다.
스스로의 능력을 키워가는 동시에 상대를 도와서 나를 이롭게 하는 것,
그것이 바로 네트워킹의 지혜이며, 상생의 원리입니다.


반응형
반응형

[보안] 잘 보이는 곳에 비밀 메시지를 숨겨보자, 스테가노그래피


http://www.bloter.net/archives/289506




스테가노그래피는 그리스어로 ‘감춰져 있다’를 뜻하는 ‘stegano’와 통신을 뜻하는 ‘graphos’가 결합한 단어다.


그 기원은 고대 그리스로 거슬러 올라간다. 기원전 440년, 그리스의 왕 히스티아에우스는 다른 나라의 인질로 잡힌다. 양아들에게 밀서를 보낼 방법을 고민하던 히스티아에우스는 노예의 머리를 깎고 두피에 비밀 메시지를 문신으로 새겨넣었다. 곧 노예의 머리카락이 자라 문신이 보이지 않게 되자 히스티아에우스는 노예를 양아들에게 보냈다. 양아들은 노예의 머리를 다시 깎아 비밀 메시지를 확인할 수 있었다. 이 일화가 문서에 기록된 인류의 첫 스테가노그래피다.


스테가노그래피는 이후 디지털 세상으로 넘어와 여러 방법으로 진화했다. 많은 사람이 암호화 기법인 크립토그래피(cryptography)와 디지털 스테가노그래피를 헷갈리지만, 둘은 상이한 기법이다. 암호화 기법은 상대방이 이해할 수 없는 내용을 작성해 그 안에 비밀을 숨겨놓는다. 반면 디지털 스테가노그래피는 이미지, 오디오 파일, 동영상 클립, 텍스트 파일 등 무해해 보이는 객체 안에 비밀 메시지를 감춰두는 방식으로 그 내용을 숨긴다. 오늘날에는 테러범 혹은 정부 첩보기관이 정보를 주고받을 때 디지털 스테가노그래피 기법을 많이 사용한다.


2001년 9·11 테러 당시 오사마 빈 라덴이 테러범들과 메시지를 주고받을 때 사용된 기법도 스테가노그래피였다. 그는 모나리자 그림에 비행기 도면을 숨겨 테러범에게 전송했다. 2011년 북한이 남한 내 간첩조직과 교신할 때도 이 기법을 사용했다.


최근 스테가노그래피는 단순히 비밀 메시지를 전달하는 목적 외에도 멀웨어를 숨기는 데 빈번하게 사용되고 있다. 보안 솔루션 기업 맥아피는 스테가노그래피 기법을 이용한 사이버 공격 사례가 그 어느 때보다 다양해지고 있다고 분석했다.

맥아피에 따르면, 사이버 공격에 스테가노그래피가 처음 사용된 것은 2011년 출현한 악성코드 ‘두쿠'(Duqu) 사례다. 두쿠는 피해자의 시스템으로부터 정보를 수집해 JPEG 파일에 숨겨 자신의 제어 서버로 전송했다. 스테가노그래피는 2014년 말 ‘러크'(Lurk)라는 멀웨어가 악성코드를 유포하는 데도 사용됐다. 최근에는 이미지 스테가노그래피가 스테고로더와 여러 멀버타이징온라인 광고를 통한 악성코드 유포.close에 사용되고 있다. 지난달에는 스테가노그래피 기법을 이용한 랜섬웨어 유포 수법이 등장하기도 했다.


스테가노그래피가 해커들이 애용하는 공격 기법으로 떠오른 이유는 대부분 안티멀웨어 탐지를 우회할 수 있어 피해 예방이 매우 어렵기 때문이다. 하지만 가능한 대응 방안들은 존재한다. 


맥아피는 

▲이미지 소프트웨어의 도움을 받아 스테가노그래피로 의심되는 색상 차이를 탐색하기 

▲스테가노그래피 공격을 받을 때를 대비해 네트워크 세분화와 가상 시스템 아키텍처를 함께 활용할 것 

▲신뢰할 수 있는 공급 업체가 제공한 서명이 있는 애플리케이션만 설치할 것 

등 대응 방안을 소개했다.


스테가노그래피, 직접 만들어보자 


악용하지만 않는다면 디지털 스테가노그래피는 나만의 비밀을 숨길 수 있는 흥미로운 기법이다. 간단한 스테가노그래피는 무료 오픈소스 도구를 이용해 간편하게 만들 수 있다.

※ 인포섹이 꼽은 최고의 무료 스테가노그래피 도구들

...

반응형
반응형

변화가 있었다면, 

아버지의 이미지는 더 실제적이고 

온전하게 되었다. 아버지는 여전히 나에게 

실망과 상처를 준 사람으로 느껴졌다. 그러나 

아버지 속에 있는 강점과 장점도 볼 수 있게 되었다. 

확신하건대, 내가 아버지에 대해 가지게 된 새로운 

이미지는 현실에 좀 더 가까운 것이었다. 



- 데이비드 스툽의《부모를 용서하기 나를 용서하기》중에서 -



* 아버지도 변해야 하지만

자식들도 많이 변화해야 합니다.

아버지를 바라보는 시선이 바뀌면

아버지의 삶에 대한 생각도 바뀌게 됩니다. 

아버지로부터 받은 실망과 상처도 강점과 장점으로 

받아들일 수 있게 됩니다. 부모를 용서하는 것이 

나를 용서하는 것이고, 부모를 사랑하는 것이 

나를 사랑하는 것입니다. 

반응형

'생활의 발견 > 아침편지' 카테고리의 다른 글

행복한 때, 불행한 때  (0) 2017.02.13
'강렬한 삶'의 첫째 조건  (0) 2017.02.13
혼자서 외로이 조용한 시간  (0) 2017.02.09
기억과 기록  (0) 2017.02.07
첫 친구에게  (0) 2017.02.06

+ Recent posts