[python] 5
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- import cv2
- import numpy as np
- import matplotlib.pyplot as plt
- # Baca gambar dan ubah ke grayscale
- I = cv2.imread('y.png', cv2.IMREAD_GRAYSCALE)
- # Operator Roberts
- Rx = np.array([[1,0], [0,-1]])
- Ry = np.array([[0,1], [-1,0]])
- # Deteksi tepi
- Jx = cv2.filter2D(I, -1, Rx)
- Jy = cv2.filter2D(I, -1, Ry)
- # Magnitudo gradien
- Jedge = np.sqrt(Jx**2 + Jy**2)
- # Segmentasi menggunakan thresholding
- threshold_value = 2 # Atur threshold sesuai kebutuhan
- segmented_image = np.where(Jedge > threshold_value, 0, 255).astype(np.uint8) # Inversi threshold
- # Temukan kontur untuk segmentasi berbasis wilayah
- contours, _ = cv2.findContours(segmented_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- # Mewarnai setiap wilayah dengan warna yang unik
- segmented_color = cv2.cvtColor(np.zeros_like(I), cv2.COLOR_GRAY2BGR)
- for i, contour in enumerate(contours):
- color = tuple(np.random.randint(0, 255, (3,)).tolist()) # Ubah ndarray ke tuple
- cv2.drawContours(segmented_color, [contour], -1, color, -1)
- # Tampilkan gambar
- plt.subplot(1, 3, 1)
- plt.imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
- plt.title('Original Image')
- plt.subplot(1, 3, 2)
- plt.imshow(Jedge, cmap='gray')
- plt.title('Edge Detection Result')
- plt.subplot(1, 3, 3)
- plt.imshow(cv2.cvtColor(segmented_color, cv2.COLOR_BGR2RGB))
- plt.title('Segmentation Result')
- plt.show()
Editor
You can edit this paste and save as new: