Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C แปลงโมเดลสี RGB เป็น HSV

ได้รับค่าสี RGB (จำนวนเต็ม 0-255) ภารกิจคือแปลงเป็นโมเดลสี HSV

โมเดลสี RGB

ประกอบด้วย Red, Green, Blue เป็น additive color model ใช้ในหน้าจอแสดงผล ผสมสี 3 สีนี้ด้วยความเข้มข้นต่างกันได้หลายล้านสี

โมเดลสี HSV

ประกอบด้วย Hue (สี), Saturation (ความอิ่มตัว), Value/Brightness (ความสว่าง) เรียกอีกอย่างว่า HSB เหมาะกับการมองเห็นของมนุษย์ ใช้กันมากในงานศิลปะ/ออกแบบ

ขั้นตอนการแปลง

  • รับค่า r, g, b (0-255)
  • หารทุกค่าด้วย 255 → ช่วง 0-1
  • หา cmax (ค่าสูงสุด), cmin (ค่าต่ำสุด), diff = cmax - cmin
  • คำนวณ Hue (h):
    • ถ้า cmax == cmin: h = 0
    • ถ้า cmax == r: h = (60 * ((g-b)/diff) + 360) % 360
    • ถ้า cmax == g: h = (60 * ((b-r)/diff) + 120) % 360
    • ถ้า cmax == b: h = (60 * ((r-g)/diff) + 240) % 360
  • คำนวณ Saturation (s):
    • ถ้า cmax == 0: s = 0
    • มิฉะนั้น: s = (diff/cmax) * 100
  • คำนวณ Value (v): v = cmax * 100

ตัวอย่าง

Input: r=31, g=52, b=29  Output: h s v = (114.78, 44.23, 20.39)
Input: r=129, g=88, b=47 Output: h s v = (30.00, 63.57, 50.59)

โค้ดตัวอย่าง

#include <stdio.h>
#include <math.h>

float max(float a, float b, float c) {
    return (a > b) ? (a > c ? a : c) : (b > c ? b : c);
}

float min(float a, float b, float c) {
    return (a < b) ? (a < c ? a : c) : (b < c ? b : c);
}

int rgb_to_hsv(float r, float g, float b) {
    float h, s, v;
    r /= 255.0; g /= 255.0; b /= 255.0;
    float cmax = max(r, g, b);
    float cmin = min(r, g, b);
    float diff = cmax - cmin;

    if (cmax == cmin) h = 0;
    else if (cmax == r) h = fmod((60 * ((g - b) / diff) + 360), 360.0);
    else if (cmax == g) h = fmod((60 * ((b - r) / diff) + 120), 360.0);
    else if (cmax == b) h = fmod((60 * ((r - g) / diff) + 240), 360.0);

    if (cmax == 0) s = 0;
    else s = (diff / cmax) * 100;

    v = cmax * 100;
    printf("h s v=(%f, %f, %f)\n", h, s, v);
    return 0;
}

int main() {
    int r = 45, g = 215, b = 0;
    rgb_to_hsv(r, g, b);
    return 0;
}

ผลลัพธ์

h s v=(107.441864, 100.000000, 84.313728)