티스토리 뷰

Coding/Python

python : 사진 분류 정리

잉_민 2022. 6. 22. 03:10
728x90
반응형

참고 : https://post.naver.com/viewer/postView.nhn?volumeNo=28851017&memberNo=34865381 

 

[출간전연재] 2. 나만의 파이썬 활용스킬 1st. _ 사진 관리

[BY 프리렉] Work 8. 사진 관리스마트폰과 같은 모바일 기기가 일반화되면서 사진 찍는 일은 일상이 ...

m.post.naver.com

 

 

1. 가상환경 설정 (그냥 데스크톱에 이것저것 설치하면 나중에 난리남 ..)

아나콘다 프롬트 

conda update conda

conda update --all

 

conda create --name meta python=3.9.7

 

conda activate meta

 

2. 파이참에서 가상환경  meta 설정

설정 - 파이썬 프로젝트 - 인터프리터 설정 - 메타

3. .py파일 생성

new -> python 파일 생성

 

 

4. PIL 없어서 오류 뜬다 설치 : 아나콘다 프롬트에서

이미지 처리해주는 라이브러리

 

5. 이미지 정보 불러오는 코드 작성

import glob

#read img path
fpath = glob.glob('photo/Camera/*.jpg')[0]


#pip3 install pillow
#image processing library
from PIL import Image
#img read
img = Image.open(fpath)

#img.size
print(img.size)
print(img.mode)

run : shift + f10 + ctrl

바로 실행 : ctrl + f5

출력 값 확인한다. 이미지 사이즈이미지 컬러 모드

 

6.사이즈 바꾸기

#img size reduce(비율 유지)
img.thumbnail((512,512))
print('re',img.size)

 

7. Exif 정보 확인

jpg 이미지의 사진 정보 = Exif

PIL 모듈은 ExifTags라는 사전이 있다.  확인해보기

from PIL import ExifTags

print(ExifTags.TAGS)

from PIL import ExifTags

##Tag = int :' 어떤 정보'
#print(ExifTags.TAGS)
##GET img's exif info
#print(img._getexif())

##ExifOffset 26
#ExifImageWidth 3000
#ExifImageHeight 2000

#한번에 처리하기
exif_data = img._getexif()

for k, v in sorted(exif_data.items()):
    print('{:5d} 0x{:04x} {}: {}'.format(k, k, ExifTags.TAGS[k], v))

 

***

8. 사진을 찍을 날짜별로 분류하기

현재 하나의 폴더에 모든 (백업) 사진이 들어가 있는데, 사진을 날짜별로 폴더에 담으려고 한다. 원래 폴더의 사진들은 그대로 놔두고 날짜별 폴더에 해당 사진들을 복사하기로 한다. 처리 절차는 다음과 같다. 여기서 원본 사진들은 [photo\Camera] 폴더에 있다고 가정하자.

1. 분류된 사진을 저장할 폴더(photo/sorted_by_date)를 하나 만든다.
2. 모든 사진에 대해서 다음 과정(3~6)을 처리한다.
3. 사진의 exif 정보를 읽는다.
4. 날짜를 추출한다.
5. 사진 저장 폴더를 (없다면) 만든다.
6. 사진을 복사한다.
import os
import glob
from PIL import Image
import shutil

#사진 담을 폴더 만든다
dest_folder = 'photo\\sorted_by_data'
if not os.path.exists(dest_folder):
    os.makedirs(dest_folder)

for fpath in glob.glob('photo\\Camera\\*.jpg'):
    # exif 정보를 읽는다
    img = Image.open(fpath)
    exif_data = img._getexif()
    img.close()

    #시간 버리고 날짜만 취한다.
    try:
        data = exif_data[0x9003].split()[0].replace(':', '-')
    except KeyError:
        #날짜 정보가 없는 사진은 건너뛴다.
        print('[SKIP]', fpath)
        continue

    #사진을 저장할 경로와 폴더를 만든다.
    fname = os.path.split(fpath)[1]
    folder2save = os.path.join(dest_folder, data)
    fpath2save = os.path.join(folder2save, fname)
    if not os.path.exists(folder2save):
        os.makedirs(folder2save)

    #사진을 복사한다. src,dst
    shutil.copyfile(fpath, fpath2save)

 

날짜별 폴더 만들어졌고 분류되어 저장
날짜읽을 수 없는 파일

 

이미지에서 특정 픽셀 위치의 (R,G,B) '값' 추출

https://minimilab.tistory.com/30

 

파이썬 Pillow 이미지 처리 (픽셀값 구하기, 누끼 이미지, 이미지 붙이기)

파이썬 Pillow 이미지 처리 (픽셀 색상 구하기, 누끼 이미지 만들기, 로고 이미지 붙이기) 파이썬 이미지 처리 라이브러리인 Pillow는 image와 관련된 다양한 처리를 할 수 있습니다. 그 중에

minimilab.tistory.com

https://kalchi09.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-%EC%82%AC%EC%A7%84%EC%9D%98-RGB-%EC%83%89%EC%83%81-%EB%B6%84%EC%84%9D%ED%95%98%EA%B8%B0

 

파이썬을 이용하여 사진의 RGB 색상 분석하기

파이썬을 사용하면 이미지를 분석하거나 약간의 보정도 가능합니다. 정말 못하는게 없는거 같습니다. 다만 파이썬을 이용하여 이미지 처리를 할 때에는 좀 색다를 라이브러리를 써야 합니다. PI

kalchi09.tistory.com

 

import os
import glob
from PIL import Image
from PIL import ExifTags
import shutil
#특정 픽셀 rgb값

print(ExifTags.TAGS)
#사진 담을 폴더 만든다
dest_folder = 'photo\\sorted_by_data'
if not os.path.exists(dest_folder):
    os.makedirs(dest_folder)



for fpath in glob.glob('photo\\ImagesForTest\\*.jpg'):
    # exif 정보를 읽는다
    img = Image.open(fpath)
    exif_data = img._getexif()
    print('here',exif_data)
    #img.close()


    rgb_im = img.convert('RGB')

    # 지정한 좌표(1, 400)의 색상을 r,g,b 변수에 넣음
    r, g, b = rgb_im.getpixel((1, 1))

    print('R,G,B',r, g, b)

 

모든 픽셀의  rgb값 .txt 파일에 저장하기

import os
import glob
from PIL import Image
from PIL import ExifTags
import numpy as np
import shutil
#모든 픽셀의  rgb값

#print(ExifTags.TAGS)
#사진 담을 폴더 만든다
dest_folder = '/Users/l.smin/PycharmProjects/pythonProject/RGB/photo/sorted_by_data'
if not os.path.exists(dest_folder):
    os.makedirs(dest_folder)



for fpath in glob.glob('/Users/l.smin/PycharmProjects/pythonProject/RGB/photo/100/*.JPG'):
    # for 폴더 내의 모든 이미지의 exif 정보를 읽어보자
    #fpath는 경로를 담고있다. + 이미지 파일 이름
    img = Image.open(fpath)
    print('img : ',fpath) #이미지 파일 정보를 출력한다
    width, height = img.size
    print('img size (W) : ',width)


    #그림 픽셀수 알기(size)
    pix = np.array(img)
    print('img size', img.size)
    #rgb mode
    rgb_im = img.convert('RGB')

    #12 세로, 1가로의 픽셀 rgb값 알기
    #print(pix[12,1])
    # 지정한 좌표(1, 1)의 색상을 r,g,b 변수에 넣음
    r, g, b = rgb_im.getpixel((1, 1))
    print('(1,1) R,G,B : ',r, g, b)

    #all pix RGB
    c=np.arange(1,width,1)
    print(c)
    #[   1    2    3 ... 4029 4030 4031]

    fname = fpath.split('/')[-1]
    text_name = fname+'.txt'
    print(text_name)
    text=open(text_name,'w+')
    #'r': 읽기
    #'w': 덮어쓰기 (+ : 파일 없으면 만들어서 작성한다.)
    #'a': 이어쓰기
    for a in c :
        for b in range(a,height) :
            # print('x,y : ',a,b)
            print(pix[b][a], file=text)
    text.close()

 

사진의 평균 rgb값 저장하기

https://inyl.github.io/programming/2017/07/31/opencv_image_color_cluster.html

 

opencv로 이미지 컬러 평균 추출하기

이번에는 opencv를 이용해서 이미지의 color feature를 추출해보겠습니다. opencv는 매우 강력한 컴퓨터 비전 라이브러리로 이미지나 동영상을 분석 & 수정등이 가능합니다. opencv는 기본적으로 c++소스

inyl.github.io

(나도 KMeans의 정의 확실히 몰라서 이 글을 참고했다.

https://hleecaster.com/ml-kmeans-clustering-concept/)

 

K-Means 클러스터링 쉽게 이해하기 - 아무튼 워라밸

본 포스팅에서는 데이터 클러스터링(군집화)로 널리 사용되는 비지도학습 알고리즘 K-Means 클러스터링에 대해 최대한 쉽게 설명해보고자 한다. 파이썬 라이브러리 scikit-learn 사용법도 간략히 소

hleecaster.com

1.설치먼저

pip3 install -U scikit-learn

pip3 install -U scikit-learn
conda install matplotlib

 

2. 코드 (이미지사이즈가 크면 연산이 오래걸려 resize 500*500해줬다)

import numpy as np
import cv2
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

image = cv2.imread("photo/100/AUNJ9016.JPG")
print(image.shape)
# (2394, 3192, 3)

#img resize
resize_img = cv2.resize(image, (500, 500))
print("resize_img.shape = {0}".format(resize_img.shape))

# 채널을 BGR -> RGB로 변경
resize_img = cv2.cvtColor(resize_img, cv2.COLOR_BGR2RGB)

resize_img = resize_img.reshape((resize_img.shape[0] * resize_img.shape[1], 3)) # height, width 통합
print('2',resize_img.shape)
# (7641648, 3)

k = 5 # 예제는 5개로 나누겠습니다
clt = KMeans(n_clusters = k)
clt.fit(resize_img)

for center in clt.cluster_centers_:
    print('3',center)

def centroid_histogram(clt):
    # grab the number of different clusters and create a histogram
    # based on the number of pixels assigned to each cluster
    numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
    (hist, _) = np.histogram(clt.labels_, bins=numLabels)

    # normalize the histogram, such that it sums to one
    hist = hist.astype("float")
    hist /= hist.sum()

    # return the histogram
    return hist


hist = centroid_histogram(clt)
print(hist)
#[ 0.68881873  0.09307065  0.14797794  0.04675512  0.02337756]

def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
                      color.astype("uint8").tolist(), -1)
        startX = endX

    # return the bar chart
    return bar

bar = plot_colors(hist, clt.cluster_centers_)


# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()

와아 짝짝짝

728x90
반응형

'Coding > Python' 카테고리의 다른 글

python : 여러 사진 파일의 RGB 평균 구하기  (0) 2022.09.10
python: 단어 빈도수 통계  (0) 2022.09.08
Python_vi편집기  (0) 2022.03.10
Python_자료형(문자열 슬라이싱)  (0) 2022.02.14
Python_자료형(딕셔너리key:Value)  (0) 2022.02.14
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함
반응형