cv2.imshow(f"Contour {index}", clone) wait_and_destroy_all_windows() def show_external_contours(image, image_gray): clone = image.copy() contours = get_contours(image_gray, cv2.RETR_EXTERNAL) cv2.drawContours(clone, contours, -1, (0, 255, 0), 2) cv2.imshow("External contours", clone) wait_and_destroy_all_windows() def show_contour_masking(image, image_gray): contours = get_contours(image_gray, cv2.RETR_EXTERNAL) for idx, contour in enumerate(contours): mask = np.zeros(image_gray.shape, dtype="uint8") cv2.drawContours(mask, [contour], -1, (255), -1) cv2.imshow("Original", image) cv2.imshow("Mask", mask) cv2.imshow(f"Masked contours: {idx}", cv2.bitwise_and(image, image, mask=mask)) wait_and_destroy_all_windows() image, image_gray = image_with_gray_arg() contours = get_contours(image_gray, cv2.RETR_LIST) show_all_contours(image, contours) show_each_contour(image, contours) show_external_contours(image, image_gray) show_contour_masking(image, image_gray)
def show_2d_br_histogram(figure, image, channels): ax = figure.add_subplot(133) hist = cv2.calcHist([channels[0], channels[2]], [0, 1], None, [32, 32], [0, 256, 0, 256]) p = ax.imshow(hist, interpolation="nearest") plt.colorbar(p) plt.xlabel("B") plt.ylabel("R") ax.set_title("BR Histogram") print(f"BR 2D Histogram shape: {hist.shape}, {hist.flatten().shape[0]}") def compute_3d_histogram(image, channels): hist = cv2.calcHist(channels, [0, 1, 2], None, [8, 16, 9], [0, 256, 0, 256, 0, 256]) print(f"3d histogram shape: {hist.shape}, " f"with {hist.flatten().shape[0]} values") image, gray_image = image_with_gray_arg() channels = cv2.split(image) cv2.imshow("Original", image) show_bgr_histogram(image, channels) fig = plt.figure() show_2d_gb_histogram(fig, image, channels) show_2d_gr_histogram(fig, image, channels) show_2d_br_histogram(fig, image, channels) compute_3d_histogram(image, channels) plt.show()
import cv2 import matplotlib matplotlib.use('macosx') from matplotlib import pyplot as plt from imageutils import image_with_gray_arg def plot_histogram(histogram, name, y_label): plt.figure() plt.title(name) plt.xlabel("Bins") plt.ylabel(y_label) plt.plot(hist) plt.xlim([0, 256]) image, image_grayscale = image_with_gray_arg() hist = cv2.calcHist([image_grayscale], [0], None, [256], [0, 256]) cv2.imshow("Grayscale", image_grayscale) plot_histogram(hist, "Grayscale Unnormalized Histogram", "# of pixels") hist /= hist.sum() plot_histogram(hist, "Grayscale L1-Normalized Histogram", "% of pixels") plt.show()