2024. 10. 31. 23:13ㆍProject
OpenCV 즉, 파이썬 라이브러리들을 가지고 이미지의 RGB값을 구하고
평균값을 산출하는 공부를 진행했습니다.
환경은 VMware에 우분투를 설치하여 테스트 환경을 구성했습니다.
VMware 우분투 환경구성이 안 된 분들은 아래 게시물 참고 하셔서 환경구성하시면 됩니다.
VMware Workstation Pro 무료 다운로드 및 설치
VMware Workstation Player는 기존에 비상업적이고 개인적인 사용을 위한 라이센스로 제공되었지만, 반도체 기업 브로드컴(Broadcom)이 VMware를 인수하게 되면서 2024년 4월 30일 이후로 Workstation Pro는 영구
peer-laboratory.tistory.com
우선 파이썬 라이브러리 설치를 위한 환경구성은
VMware에 우분투 22.04.4LTS 버전을 설치하여 환경을 구성했다.
파이썬 라이브러리 설치를 위해 우선 Python3 설치를 진행했다.
apt install python3-pip
이미지의 RGB값 평균산출을 위한 파이썬 스크립트를 실행하기 위해서는 필요한 패키지들을 설치해 주었다.
pip install numpy
pip install scikit-learn
pip install matplotlib
위 명령어를 사용하여 numpy, scikit-learn, matplotlib 패키지의 설치를 수행하였다.
메모장을 열어서 아래 코드를 삽입한 뒤에
"이름.py" 로 저장하면 파이썬 스크립트 파일이 생성된다.
아래 코드 중 image_path = 뒤 경로는
테스트를 진행할 이미지파일의 경로를 넣어주면 된다.
color_definitions = { 이 뒤에는 색상을 정의}, color_grades = { 이 부분에는 등급을 정의} 하여
코드를 완성하면 된다. 파일형식(.jpg, .png)도 꼭 넣어줘야 한다.
import numpy as np
import cv2
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
image_path = "/샘플 이미지 경로/이미지 이름.png"
image = cv2.imread(image_path)
if image is None:
print("이미지를 읽을 수 없습니다. 경로를 확인하세요.")
exit()
print(image.shape)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mask = np.all(image != [255, 255, 255], axis=-1)
filtered_image = image[mask]
image_array = filtered_image.reshape((filtered_image.shape[0], 3))
print(image_array.shape)
k = 5
clt = KMeans(n_clusters=k)
clt.fit(image_array)
centroids = clt.cluster_centers_
for center in centroids:
print(center)
def centroid_histogram(clt):
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
return hist
hist = centroid_histogram(clt)
print(hist)
average_color = np.dot(hist, centroids)
print("평균 색상값:", average_color)
color_definitions = {
" 이 부분에는 색상을 정의"
}
color_grades = {
" 이 부분에는 등급을 정의"
}
def get_closest_color_grade(avg_color):
min_distance = float('inf')
closest_grade = 0
closest_color_name = ""
for color_name, color in color_definitions.items():
distance = np.linalg.norm(avg_color - color)
if distance < min_distance:
min_distance = distance
closest_grade = color_grades[color_name]
closest_color_name = color_name
return closest_color_name, closest_grade
closest_color_name, color_grade = get_closest_color_grade(average_color)
print(f"가장 가까운 색상: {closest_color_name}, 평균 색상의 해당 등급: {color_grade}")
def plot_colors(hist, centroids):
bar = np.zeros((50, 300, 3), dtype="uint8")
startX = 0
for (percent, color) in zip(hist, centroids):
endX = startX + (percent * 300)
bar[:, int(startX):int(endX)] = color.astype("uint8")
startX = endX
return bar
bar = plot_colors(hist, clt.cluster_centers_)
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
샘플이미지는 오픈 이미지나 구글 등 저작권 문제가 없는 이미지를 사용하였다.
위 파이썬 스크립트를 우분투 터미널에서 실행해 주면 된다.
위와 같이 이미지의 포함되어 있는 색상이 바 형태로 생성되며,
코드에서 정의해 준 색상과 근사치값의 색상의 등급을 출력하게 된다.
이 프로젝트는 VMware를 다운로드하고 설치하여 우분투를 구축된 환경에서 파이썬 라이브러리를 사용한 이미지 RGB값 평균을 산출하는 과정을 다룹니다. 질문이나 추가적인 도움이 필요하시면 언제든지 댓글로 남겨주세요! 😊
'Project' 카테고리의 다른 글
Spring Tool Suite3 다운로드 및 환경설정 (2) | 2025.04.23 |
---|---|
'Syft'를 사용해 디지털 의료기기 SBOM 구현 (1) | 2024.11.27 |
[Hyperledger fabric] 2.1 Couchdb (로그인 오류 해결) (2) | 2024.10.18 |
VMware Workstation Pro 무료 다운로드 및 설치 (8) | 2024.10.15 |
[Hyperledger fabric] 3. Explorer 구축 (0) | 2024.10.09 |