Skip to content

Instantly share code, notes, and snippets.

@XinyueZ
Last active February 13, 2022 20:13
Show Gist options
  • Select an option

  • Save XinyueZ/5c879ec7b5c7c9c3e3e87b7a4d89c692 to your computer and use it in GitHub Desktop.

Select an option

Save XinyueZ/5c879ec7b5c7c9c3e3e87b7a4d89c692 to your computer and use it in GitHub Desktop.
Simple segmentation(CV)
import matplotlib.pyplot as plt
import cv2
import numpy as np
!wget https://dl.dropbox.com/s/i1e1brycec3hy3k/pilot-view.jpeg -O pilot-view.png
# For this evalution, we assume that we load image with 3 channels.
def toRGB(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def extract_hist(img):
list = []
_, _, C = img.shape
for i in range(C):
list.append(cv2.calcHist([img], [
i], None, [256], [0, 256]))
return list, ["black"] if C == 1 else ["red", "green", "blue"]
pilot_view_img = toRGB(cv2.imread("pilot-view.png"))
print(pilot_view_img.shape)
M, N, C = pilot_view_img.shape
# For this evalution, we assume that we load image with 3 channels.
assert C == 3
# Show the interesting starts with contrast and high brightness background
pilot_view_neg_img = cv2.convertScaleAbs(pilot_view_img, alpha=-1, beta=255)
plt.imshow(pilot_view_neg_img)
plt.show()
# The digital image has intensity valus of each pixel from 0~255, #size:256
intensity_values = np.arange(256)
# Extract the intensity distributions of all channels of each pixels
hist_list, colors = extract_hist(pilot_view_img)
# Extract pixels which have high intensity (brightness)
# The output image has pixel gray intensity 255 when the same pixel position of input has intensity >= 150, otherwise 0.
# For the label output the pixel given 255 has label "1", else "0".
_, result = cv2.threshold(pilot_view_img, 150, 255, cv2.THRESH_BINARY)
print(f"result shape {result.shape}")
plt.figure(figsize=(20, 20))
plt.subplot(131)
plt.title("origin")
plt.imshow(pilot_view_img)
plt.subplot(132)
plt.title("segmentation result")
plt.imshow(result)
plt.show()
# Let's compare the distribution of inensitiy distrubution
# Intensity distribution of origin image
plt.figure(figsize=(15, 4))
hist_orign_list, colors = extract_hist(pilot_view_img)
for i, hist, in enumerate(hist_orign_list):
plt.subplot(1, len(hist_orign_list), i+1)
plt.title(f"{colors[i]} channel #{i+1}")
plt.bar(intensity_values, hist[:, 0], color=[colors[i]])
plt.show()
# Intensity distribution of result
plt.figure(figsize=(15, 4))
hist_result_list, colors = extract_hist(result)
for i, hist, in enumerate(hist_result_list):
plt.subplot(1, len(hist_result_list), i+1)
plt.title(f"Channel {i+1}")
plt.bar(intensity_values, hist[:, 0], color=[colors[i]])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment