streamlit-hsv-segment.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import cv2
  2. import numpy as np
  3. import streamlit as st
  4. from ads import css_string
  5. def segment_color(img, lb, ub):
  6. hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  7. color_mask = cv2.inRange(hsv_img, np.array(lb), np.array(ub))
  8. return color_mask
  9. # Create application title and file uploader widget.
  10. st.title("Color Segmentation using OpenCV")
  11. buffer = st.file_uploader('Select Image', type=['jpg', 'jpeg', 'png'])
  12. st.sidebar.header('STEPS:')
  13. st.sidebar.text("1️⃣ Upload image")
  14. st.sidebar.text("2️⃣ Select color")
  15. st.sidebar.text("3️⃣ Adjust sliders")
  16. st.sidebar.text(" ")
  17. st.sidebar.markdown(css_string, unsafe_allow_html=True)
  18. upper_bound = []
  19. lower_bound = []
  20. line_hsv = cv2.imread('hsv-line.png')
  21. if buffer is not None:
  22. raw_bytes = np.asarray(bytearray(buffer.read()), dtype=np.uint8)
  23. # Loads image in a BGR channel order.
  24. image = cv2.imdecode(raw_bytes, cv2.IMREAD_COLOR)
  25. # Create placeholders to display input and output images.
  26. placeholders = st.columns(2)
  27. # Display Input image in the first placeholder.
  28. placeholders[0].image(image, channels='BGR')
  29. placeholders[0].text("Input Image")
  30. st.image(line_hsv, channels='BGR')
  31. hue = st.slider('Hue', 0, 255, [0, 40])
  32. sat = st.slider('Saturation', 0, 255, [70, 255])
  33. val = st.slider('Lightness', 0, 255, [70, 255])
  34. lower_bound = [hue[0], sat[0], val[0]]
  35. upper_bound = [hue[1], sat[1], val[1]]
  36. mask = segment_color(image, lower_bound, upper_bound)
  37. # Display mask.
  38. placeholders[1].image(mask)
  39. placeholders[1].text('Color Mask')
  40. hide_streamlit_style = """
  41. <style>
  42. footer {visibility: hidden;}
  43. </style>
  44. """
  45. st.markdown(hide_streamlit_style, unsafe_allow_html=True)