Transform Bounded Color and Audio Fixtures
Core idea
colorsys converts normalized RGB coordinates to HSV, HLS and other color representations; for RGB and HSV, coordinates are between zero and one. wave reads and writes uncompressed PCM WAV data. Channel count, sample width in bytes and sample rate determine how to interpret audio frames. Use small in-memory fixtures to test conversions without external media files.
import colorsysrgb = (0.2, 0.4, 0.6)hsv = colorsys.rgb_to_hsv(*rgb)restored = colorsys.hsv_to_rgb(*hsv)print(tuple(round(x, 3) for x in hsv))print(all(abs(a-b)<1e-9 for a,b in zip(rgb,restored)))The hue is a fraction of a turn, not degrees; approximate comparison handles rounding.
Expected output:
(0.583, 0.667, 0.6)TrueWrite and read a tiny PCM sample
import io, wavestream = io.BytesIO()with wave.open(stream, 'wb') as f: f.setnchannels(1) f.setsampwidth(2) f.setframerate(8000) f.writeframes(b'\x00\x00\x01\x00')stream.seek(0)with wave.open(stream, 'rb') as f: print(f.getnframes(), f.getframerate()) print(len(f.readframes(2)))Two mono frames of two bytes each occupy four data bytes. No playback or sound hardware is required.
Expected output:
2 80004Common mistake
Do not pass 0–255 RGB integers directly to normalized conversion functions. WAV is a container, not a promise that every codec is supported by wave. Bound frame counts before reading untrusted media.
Practice
Normalize (255,128,0), round-trip through HSV and compare within tolerance. Write a four-frame mono PCM fixture and confirm its sample width and frame count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Media and color helpers
Check your understanding of media and color helpers.
What is printed?
import colorsysprint(colorsys.hsv_to_rgb(0,1,1))What is printed?
print(2*2*3)How should RGB byte channels be prepared for colorsys?
What does wave support here?