<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Khokhwan Weangoukost</title>
    <description>The latest articles on DEV Community by Khokhwan Weangoukost (@khokhwan).</description>
    <link>https://dev.to/khokhwan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1402240%2F8b30760f-40ac-4638-a397-61ee09e41970.JPG</url>
      <title>DEV Community: Khokhwan Weangoukost</title>
      <link>https://dev.to/khokhwan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/khokhwan"/>
    <language>en</language>
    <item>
      <title>สร้างโค้ดสีจากรูปภาพ โดยใช้ Python</title>
      <dc:creator>Khokhwan Weangoukost</dc:creator>
      <pubDate>Wed, 10 Apr 2024 17:45:08 +0000</pubDate>
      <link>https://dev.to/khokhwan/sraangokhdsiicchaakruupphaaph-odyaich-python-dej</link>
      <guid>https://dev.to/khokhwan/sraangokhdsiicchaakruupphaaph-odyaich-python-dej</guid>
      <description>&lt;p&gt;สายกราฟฟิก หรือสาย Web designer คนไหนเคยอยากคุมโทนสีตามเรฟที่เป็นรูปภาพ แต่ดูดสีออกมายังไงก็ไม่ได้ดั่งใจไหมคะ? เดี๋ยวเราจะพามาให้รู้จักกับ K-means Algorithm ที่จะทำให้ชีวิตเราง่ายขึ้นเยอะะ เพราะสามารถดูดสีออกมาได้เป๊ะอย่างงี้ 👍🏼💯 &lt;/p&gt;

&lt;p&gt;บทความนี้เราจะทำการดูดสีรูปภาพโดยใช้ K-mean Clustering ( ในส่วนของ Image Processing ☝🏼🖼️ ) ในการตรวจจับกลุ่มสีต่าง ๆ ในรูป เพื่อนำค่า RGB ของจุดศูนย์กลางของกลุ่มสีนั้น ๆ มาสร้างเป็นโค้ดสี โดยทั้งหมดเราจะรันโค้ดผ่าน Google Colab &lt;/p&gt;

&lt;h2&gt;
  
  
  ✍🏻 ขั้นตอนที่ 1 : Import Libraries
&lt;/h2&gt;

&lt;p&gt;ทำการเรียกใช้ไลบรารีที่จำเป็น ดังนี้&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scikit-learn ไลบรารีหลักสำหรับ Machine Learning ในภาษา Python ที่มีฟังก์ชันการทำงานที่ครอบคลุม และรองรับอัลกอริธึมที่หลากหลาย ซึ่งแน่นอนว่าการจัดกลุ่ม (Clustering) ก็เป็นหนึ่งในนั้น&lt;/li&gt;
&lt;li&gt;Matplotlib สำหรับสร้างกราฟวงกลม (Pie Chart)&lt;/li&gt;
&lt;li&gt;NumPy (Numerical Python) สำหรับการจัดการ Array&lt;/li&gt;
&lt;li&gt;OpenCV (Open Source Computer Vision Library) สำหรับการจัดการรูปภาพ&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import cv2
from collections import Counter
from skimage.color import rgb2lab, deltaE_cie76
import os

%matplotlib inline


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  ✍🏻 ขั้นตอนที่ 2 : นำเข้าข้อมูลรูปภาพ
&lt;/h2&gt;

&lt;p&gt;เลือกรูปที่สนใจมา 1 รูป โดยในตัวอย่างนี้จะใช้เป็นรูปน้องหนูเจอรี่ 🤓👇🏻&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1tqpu0p9vwwvlzy3ptp.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh1tqpu0p9vwwvlzy3ptp.JPG" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;เมื่อนำรูปจากไดรฟ์เข้ามาแล้ว จะทำการอ่านและเก็บไว้ในตัวแปร image&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

from google.colab import drive

drive.mount('/content/drive')
file_path = '/content/drive/MyDrive/hey.JPG'

image = cv2.imread(file_path)
print("The type of this input is {}".format(type(image)))
print("Shape: {}".format(image.shape))
plt.imshow(image)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw6o5emsos2k6ru3k1aaa.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw6o5emsos2k6ru3k1aaa.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;แต่เราจะสังเกตได้ว่ารูปที่ได้สีจะเพี้ยนไปจากรูปตัวอย่าง เพราะว่าการอ่านรูปของ OpenCV โดย default ทำให้เราได้รูปออกมาเป็น BGR &lt;/p&gt;

&lt;p&gt;ดังนั้น เราจะทำการเปลี่ยนให้เป็น RGB ด้วย&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ก็จะได้แบบนี้&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1wrgmau50i0g51fhjocb.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1wrgmau50i0g51fhjocb.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;เมื่อสีรูปตรงกับต้นฉบับแล้ว เราก็ไปดูดสีกันได้เลยย 🙌🏼&lt;/p&gt;

&lt;h2&gt;
  
  
  ขั้นตอนที่ 3 : สร้างฟังก์ชันจำแนกสี
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;สร้างฟังก์ชันให้สีที่จำแนกออกมาอยู่ในรูปของค่า hex (โค้ดสี)&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;สร้างฟังก์ชันวิเคราะห์ค่าสีออกมา&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

def get_colors(image, number_of_colors, show_chart):

    modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)
    modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)

    clf = KMeans(n_clusters = number_of_colors)
    labels = clf.fit_predict(modified_image)

    counts = Counter(labels)
    # sort to ensure correct color percentage
    counts = dict(sorted(counts.items()))

    center_colors = clf.cluster_centers_
    # We get ordered colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]

    if (show_chart):
        plt.figure(figsize = (8, 6))
        plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)

    return rgb_colors


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  ขั้นตอนที่ 4 : ทดลองนำมาใช้กับรูปตัวอย่าง
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

get_colors(image, 8, True)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqe5ty8s8nkddz1gb0thz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqe5ty8s8nkddz1gb0thz.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;❔ &lt;strong&gt;คำถามชวนคิด&lt;/strong&gt; ❔&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;จากผลลัพธ์ข้างต้น คิดว่าถ้าเราสามารถดูดสีจากรูปได้ เราจะสามารถดูดรูปจากสีได้เหมือนกันไหม 🧐&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;มาลองดูกันน! 😼💪🏻&lt;/p&gt;

&lt;h2&gt;
  
  
  ขั้นตอนสำหรับการค้นหารูปจากโค้ดสี
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;ก่อนอื่นเราจะต้องมีคลังรูปภาพไว้ใน images ก่อน&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

IMAGE_DIRECTORY = '/content/drive/MyDrive/gallery'
COLORS = {
    'RED': [255, 0, 0],
    'BLUE': [0, 0, 128],
    'YELLOW': [255, 255, 0]
}
images = []

for file in os.listdir(IMAGE_DIRECTORY):
    if not file.startswith('.'):
        images.append(get_image(os.path.join(IMAGE_DIRECTORY, file)))


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ลองแสดงรูปภาพทั้งหมดในแกลลอรี่&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

plt.figure(figsize=(20, 10))
for i in range(len(images)):
    plt.subplot(1, len(images), i+1)
    plt.imshow(images[i])


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd1eip122uca1nlecvrma.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd1eip122uca1nlecvrma.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ต่อมาสร้างฟังก์ชันที่จะเลือกจับคู่สีหลัก ๆ ของรูปภาพมา 10 สี จากนั้นจะเอา 5 สีแรกจากรูปมาคำนวณหาความแตกต่างกับสีที่เราต้องการ&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;ซึ่งแน่นอนว่าเราไม่สามารถจับคู่ค่าสี (hex) ได้ตรงเป๊ะ ดังนั้น เราจะดูจากสัดส่วนค่าความต่างสี ถ้าน้อยแสดงว่าทั้งสองสีมีความใกล้เคียงกัน เราก็จะแสดงรูปนั้นเลย เพื่อประกาศว่าสีตรงกับรูปนี้นะ&lt;/p&gt;

&lt;p&gt;โดยเราจะใช้ &lt;code&gt;rgb2lab&lt;/code&gt; เพื่อแปลงค่าให้สามารถนำมาเปรียบเทียบกันได้ และใช้ &lt;code&gt;deltaE_cie76&lt;/code&gt; สำหรับการหาความต่างสี ได้ดังนี้&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

def match_image_by_color(image, color, threshold = 60, number_of_colors = 10): 

    image_colors = get_colors(image, number_of_colors, False)
    selected_color = rgb2lab(np.uint8(np.asarray([[color]])))

    select_image = False
    for i in range(number_of_colors):
        curr_color = rgb2lab(np.uint8(np.asarray([[image_colors[i]]])))
        diff = deltaE_cie76(selected_color, curr_color)
        if (diff &amp;lt; threshold):
            select_image = True

    return select_image

def show_selected_images(images, color, threshold, colors_to_match):
    index = 1

    for i in range(len(images)):
        selected = match_image_by_color(images[i],
                                        color,
                                        threshold,
                                        colors_to_match)
        if (selected):
            plt.subplot(1, 5, index)
            plt.imshow(images[i])
            index += 1


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;จากนั้นทดลองหารูปที่มีสีแดง ❤️&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

# Search for RED
plt.figure(figsize = (20, 10))
show_selected_images(images, COLORS['RED'], 60, 5)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnjhmxybpdrqxypxl2wdg.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnjhmxybpdrqxypxl2wdg.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;ทดลองหารูปที่มีสีฟ้า💙&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

# Search for BLUE
plt.figure(figsize = (20, 10))
show_selected_images(images, COLORS['BLUE'], 60, 5)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe3j2ne8ub4dllrwhpieh.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe3j2ne8ub4dllrwhpieh.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;ทดลองหารูปที่มีสีเหลือง💛&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

# Search for YELLOW
plt.figure(figsize = (20, 10))
show_selected_images(images, COLORS['YELLOW'], 60, 5)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;ผลลัพธ์ที่ได้&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9h63x9kkgsl0rowaxo7s.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9h63x9kkgsl0rowaxo7s.jpg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;สรุปผล 👩🏻‍🎨🗯️&lt;/strong&gt;&lt;br&gt;
เราสามารถดึงสีมาจากรูปได้โดยการใช้ K-mean Clustering แต่ในทางกลับกันหากนำโค้ดมาทำการค้นหารูปก็อาจจะไม่สามารถทำได้ดีเท่าที่ควร เห็นได้จากตอนค้นหารูปที่มีสีฟ้า มีการแสดงทุกรูปที่มีออกมาเลย ส่วนนึงเนื่องมาจากการเทียบโค้ดสี hex ให้ตรงกันนั้นเป็นไปได้ยาก จึงง่ายต่อการคลาดเคลื่อน หรือก็คืออาจจะได้รูปที่ไม่ตรงกับสีที่ค้นหา&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference :&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/kb22/Color-Identification-using-Machine-Learning/blob/master/Color%20Identification%20using%20Machine%20Learning.ipynb" rel="noopener noreferrer"&gt;Color Identification using Machine Learning by kHarshit
and Harshit Kumar&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Images by &lt;a href="https://www.freepik.com" rel="noopener noreferrer"&gt;Freepik&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
  </channel>
</rss>
