import cv2 import matplotlib.pyplot as plt def plot_histogram_and_draw_lines(image_path, column_indices, y_range): # 讀取圖像 image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 檢查圖像是否成功讀取 if image is None: print(f"Error: Unable to read the image '{image_path}'.") return # 打印圖像大小 print("Image shape:", image.shape) # 創建彩色圖像以便畫線 image_color = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) for column_index in column_indices: # 檢查 column_index 是否在圖像範圍內 if column_index >= image.shape[1]: print(f"Error: column_index {column_index} is out of bounds for image width {image.shape[1]}.") continue # 檢查 y_range 是否在圖像範圍內 if max(y_range) >= image.shape[0]: print(f"Error: y_range exceeds image height {image.shape[0]}.") continue # 選擇特定的列和 y 坐標範圍 column_data = image[y_range, column_index] # 反轉 y 坐標範圍 y_coordinates_reversed = list(y_range)[::-1] # 檢查 column_data 的值 unique_values = set(column_data) print(f"\nUnique grayscale values in the selected range for column {column_index}: {unique_values}") # 打印每段的開始和結束點 print(f"Y-coordinate start: {y_coordinates_reversed[0]}, Grayscale Value start: {column_data[0]}") print(f"Y-coordinate end: {y_coordinates_reversed[-1]}, Grayscale Value end: {column_data[-1]}") # 查找從灰度值 250 開始並遵循規則的最高點 start_index = next((i for i, value in enumerate(column_data) if value <= 250), None) if start_index is None: print("No grayscale value below or equal to 250 found in the selected range.") continue start_y_coord = y_coordinates_reversed[start_index] start_grayscale_value = column_data[start_index] print(f"Start point: Y-coordinate: {start_y_coord}, Grayscale Value: {start_grayscale_value}") decreasing = True highest_point = None potential_highest = None for i in range(start_index, len(column_data) - 40): current_value = column_data[i] next_values = column_data[i + 1:i + 5] #4 if decreasing: if all(next_value > current_value for next_value in next_values): decreasing = False potential_highest = (y_coordinates_reversed[i + 3], column_data[i + 3]) else: if all(next_value > potential_highest[1] for next_value in next_values): potential_highest = (y_coordinates_reversed[i + 2], column_data[i + 2]) elif all(next_value < current_value for next_value in next_values): highest_point = potential_highest break if highest_point: highest_y_coord, highest_grayscale_value = highest_point print( f"Highest point after decrease and subsequent increase: Y-coordinate: {highest_y_coord}, Grayscale Value: {highest_grayscale_value}") # 計算並打印Y坐標的差值 y_difference = start_y_coord - highest_y_coord print(f"Y-coordinate difference: {y_difference}") # 計算並打印Y坐標差值乘以2.4/1000的結果 result = y_difference * 2.4 / 1000 print(f"Result: {result}") # 在圖像上畫線,從起點畫到最高點 cv2.line(image_color, (column_index, image.shape[0] - start_y_coord), (column_index, image.shape[0] - highest_y_coord), (0, 0, 255), 1) # 在圖像上顯示結果值 text_position = (column_index, image.shape[0] - highest_y_coord - 10) cv2.putText(image_color, f'Result: {result:.4f}mm', text_position, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1) else: print("No valid highest point found following the specified rules.") # 繪製直方圖 # plt.plot(column_data, y_coordinates_reversed, color='gray') # plt.xlabel('Pixel Intensity') # plt.ylabel('Y-axis Coordinate (Reversed)') # plt.title(f'Grayscale Distribution at X-axis = {column_index} (Y-coordinate: {y_range.start}-{y_range.stop})') # plt.show() # 顯示並保存帶有畫線的圖像 plt.imshow(cv2.cvtColor(image_color, cv2.COLOR_BGR2RGB)) plt.title('Image with lines') plt.show() cv2.imwrite('image_with_lines.png', image_color) if __name__ == '__main__': # image_path = r"02_1_20000.bmp" image_path = r"D:\Code\Project\Medeologix\Python\Size\TIS_test\joe\516\01_1_20000.bmp" x_range = 5472 num_segments = 10 column_indices = [x * x_range // num_segments for x in range(num_segments)] y_range_partial = range(0, 3648) # 嘗試不同的範圍 plot_histogram_and_draw_lines(image_path, column_indices, y_range_partial)