뎁스_2599

뎁스_2599

뎁스_2599뎁스_2599· 1년

질문제 코드에서 무엇이 잘못되었을까요? ㅜㅜ

안녕하세요, 현재 파이썬 독학을 하고 있는 사람입니다. python으로 treemap을 만들고자 하는 문제를 풀고 있는데, 답이 자꾸 나오지 않아서 무엇이 문제인지 파악하고 싶습니다! (time out 문제도 같이 발생하고 있습니다.) 문제의 로직은 아래와 같습니다. **1단계: 정렬** 여기에는 특정 방정식이 없습니다. 데이터 포인트 목록을 값의 내림차순으로 정렬하면 됩니다. (helper function 사용) 2단계: 레이아웃 초기화 방향을 결정합니다. orientation={left edge: ​if bounding box width ≥ bounding box height top edge: otherwise​ **3단계: 행 형성** For each value of k: 1) Calculate row fraction: row fraction= sum of values of first k data points / sum of all values in the list 2) Calculate individual fractions: fraction(i) = value of data point i / sum of values of first data points 3) Calculate heights and widths: ​height(i) =row fraction × bounding box height × fraction(i) width(i) = row fraction × bounding box width × fraction(i) 4) Calculate aspect ratios: aspect ratio(i) = max(width(i), height(i)) / min(width(i), height(i)) 5) Calculate distortion: distortion = max(aspect ratios) 각 값에 대해 : 1. 순서가 지정된 처음 k개의 데이터 포인트를 가져와 해당 값을 합산합니다. 그런 다음 전체 목록에 있는 모든 값의 합으로 나눕니다. 이 분수는 이 직사각형 행이 차지해야 하는 경계 상자 영역의 분수입니다. 2. k개의 데이터 포인트 각각에 대해 해당 값을 k개의 합으로 나눕니다. 행의 값. 이는 이 데이터 포인트의 직사각형이 차지해야 하는 행 영역의 비율입니다. 행의 직사각형은 위에서 아래로(행이 경계 상자의 왼쪽 가장자리에 있는 경우) 또는 왼쪽에서 오른쪽으로(행이 위쪽 가장자리에 있는 경우) 배치됩니다. 3. 위의 계산을 통해 행에 있는 각 직사각형의 높이와 너비를 결정할 수 있습니다. 긴 변을 짧은 변으로 나누어 각 직사각형의 종횡비를 계산합니다. 종횡비는 1보다 크거나 같은 숫자입니다. 여기서 1은 직사각형이 정사각형임을 의미하고, 종횡비가 매우 높으면 직사각형이 매우 왜곡되었음을 의미합니다. 4. 이 행의 왜곡을 행에 있는 직사각형의 최대 종횡비로 정의합니다. 5. k= 1인 경우 또는 이 행에 대한 왜곡이 이전 k에 대한 왜곡보다 작거나 같은 경우, 다음으로 넘어가세요. k의 다음 값이 없는 경우 이 행은 이미 목록의 모든 데이터 포인트를 사용하고 있으므로 프로세스를 중지하고 이 k 값을 유지합니다. (왜곡이 가장 낮습니다). 반면, 이전 k에 비해 왜곡이 더 크다면, 우리는 다음 k로 넘어가지 않을 것입니다 현재 k를 유지하지도 않음. 대신 프로세스를 중지하고 이전 k 값을 선택하십시오. (왜곡이 가장 적은 것). ** 재귀함수로 풀 것 ** 제가 만들고자 하는 function은 compute_rectangles(t, bounding_rec_width=1.0, bounding_rec_height=1.0) 이며, 제가 만들어야하는 function과 제가 만든 코드는 아래와 같습니다. (parameter 변경 불가, helper function 만들어서 풀어야함) def compute_rectangles(t, bounding_rec_width=1.0, bounding_rec_height=1.0): ''' Computes the rectangles for drawing a treemap of the provided tree. Inputs: t: (Tree) a tree bounding_rec_width, bounding_rec_height: (float) the width and height of the bounding rectangle. Returns: a list of Rectangle objects. ''' rectangles = [] # Initialize the list of rectangles stack = [(t, bounding_rec_width, bounding_rec_height)] # Initialize a stack for iterative processing while stack: current_tree, current_width, current_height = stack.pop() if not current_tree.children: # Base case: if the tree is a leaf, create a rectangle and add it to the list origin = (0.0, 0.0) # Set a default origin for the leaf node rectangles.append(Rectangle(origin, (current_width, current_height), current_tree.key)) else: # Sort the children of the tree sorted_tree_list = sorted_trees(current_tree.children) # Initialize the list of rectangles for the current tree row_layout = [] # Get the next row layout and leftover rectangle for tree in sorted_tree_list: # Calculate aspect ratio for each rectangle in the row row_sum = tree.value if not row_layout else sum(child[0].value for child in row_layout) + tree.value row_fraction = row_sum / sum(child.value for child in sorted_tree_list) width = row_fraction * current_width # Calculate width for each rectangle in the row height = row_fraction * current_height aspect_ratio = max(width, height) / min(width, height) # Check if adding the current rectangle improves the aspect ratio if not row_layout or aspect_ratio <= row_layout[-1][1]: row_layout.append((tree, aspect_ratio, width, height)) else: break # Recursively call the function for the current tree's children for child, _, child_width, child_height in row_layout: stack.append((child, child_width, child_height)) return rectangles 원하는 답은 이런 형식입니다. data_rectangles = {'birds': {'Apr': <tree.Tree object at 0x7faa9edaa3d0>, 'Aug': <tree.Tree object at 0x7faa9ed06cd0>, 'Dec': <tree.Tree...ect at 0x7faa9efd3b20>, 'Dec': <tree.Tree object at 0x7faa9f064070>, 'Feb': <tree.Tree object at 0x7faa9efce940>, ...}} key = 's1' @pytest.mark.parametrize("key", TEST_KEYS) def test_compute_rectangles_flat(data_rectangles, key): expected_recs = [{'color_code': [''], 'height': 0.5, 'label': 'B40', 'width': 0.8, ...}, {'color_code': [''], 'height': 0.5, 'label': 'C40', 'width': 0.8, ...}, {'color_code': [''], 'height': 1.0, 'label': 'D20', 'width': 0.19999999999999996, ...}] 혹은 ipython3으로 실행했을 경우, In [14]: data_flat = treemap.load_trees('data/sparrows.json') In [15]: recs = treemap.compute_rectangles(data_flat['s1']) In [16]: for r in recs: ...: print(r) ...: # x, y, width, height, label 순입니다. RECTANGLE 0.0000 0.0000 0.8000 0.5000 B40 RECTANGLE 0.0000 0.5000 0.8000 0.5000 C40 RECTANGLE 0.8000 0.0000 0.2000 1.0000 D20 In [17]: recs = treemap.compute_rectangles(data_flat['s2']) In [18]: for r in recs: ...: print(r) ...: RECTANGLE 0.0000 0.0000 0.6000 0.5000 Six (a) RECTANGLE 0.0000 0.5000 0.6000 0.5000 Six (b) RECTANGLE 0.6000 0.0000 0.4000 0.3750 Three RECTANGLE 0.6000 0.3750 0.4000 0.2500 Two RECTANGLE 0.6000 0.6250 0.2667 0.1875 One (a) RECTANGLE 0.6000 0.8125 0.2667 0.1875 One (b) RECTANGLE 0.8667 0.6250 0.1333 0.3750 One (c) In [19]: recs = treemap.compute_rectangles(data_flat['s3']) In [20]: for r in recs: ...: print(r) ...: RECTANGLE 0.0000 0.0000 0.5000 0.5000 6 RECTANGLE 0.0000 0.5000 0.5000 0.5000 6 RECTANGLE 0.5000 0.0000 0.5000 0.3333 4 RECTANGLE 0.5000 0.3333 0.5000 0.2500 3 RECTANGLE 0.5000 0.5833 0.4000 0.2083 2x RECTANGLE 0.5000 0.7917 0.4000 0.2083 2y RECTANGLE 0.9000 0.5833 0.1000 0.4167 1 # data_flat['s2']는 트리입니다. 그리고 helper functions(sorted_trees(tree_list), compute_row(bounding_rec, row_data, total_sum))과 class Rectangle는 아래와 같습니다. class Rectangle: ''' Simple class for representing rectangles. Attributes: x, y: (float) coordinates of rectangle's origin width, height: (float) the rectangle's width and height label: (str) text label for the rectangle color_code: (tuple) tuple for determining what color the rectangle should be ''' def __init__(self, origin, size, label="", color_code=("",)): ''' Constructs a new Rectangle. Inputs: origin: (pair of float) x and y coordinates of the rectangle's origin size: (pair of float) the width and height of the rectangle ''' # Validate parameters validate_tuple_param(origin, "origin") validate_tuple_param(origin, "size") assert label is not None, "Rectangle label can't be None" assert isinstance(label, str), "Rectangle label must be a string" assert color_code is not None, "Rectangle color_code can't be None" assert isinstance(color_code, tuple), \ "Rectangle color_code must be a tuple" self.x, self.y = origin self.width, self.height = size self.label = label self.color_code = color_code def __str__(self): format_string = "RECTANGLE {:.4f} {:.4f} {:.4f} {:.4f} {}" return format_string.format(self.x, self.y, self.width, self.height, self.label) def __repr__(self): return str(self) def sorted_trees(tree_list): ''' Sort a list of Tree instances by the value of their roots in descending order. Ties are broken by the key of the root, in (forward) alphabetical order. Returns a new sorted list without modifying the input list. Inputs: tree_list: list of Tree instances, each with an integer value. Returns: list of Tree instances, sorted. ''' return sorted(tree_list, key=lambda t: (-t.value, t.key)) def compute_row(bounding_rec, row_data, total_sum): ''' Lay out the given data points as rectangles in one row of a treemap. The row will be against the left or top edge of the bounding rectangle, depending on whether the rectangle is at least as wide as it is tall. Inputs: bounding_rec: (Rectangle) the bounding rectangle row_data: (list of Tree) the list of data points that should be included in this row. total_sum: (integer) the total value of all the rectangles that will eventually fill the bounding rectangle (not just those in this row). Returns: a tuple (row_layout, leftover_rec), where row_layout: list of pairs (rec, t), where rec is a Rectangle, and t is the Tree that Rectangle corresponds to, and leftover_rec: a Rectangle representing the leftover space in the bounding rectangle that was not used by this row. ''' if bounding_rec.width >= bounding_rec.height: return __compute_row_wide(bounding_rec, row_data, total_sum) else: row_layout_t, leftover_rec_t = __compute_row_wide( __transpose_rectangle(bounding_rec), row_data, total_sum) row_layout = [(__transpose_rectangle(rec), tr) for rec, tr in row_layout_t] leftover_rec = __transpose_rectangle(leftover_rec_t) return row_layout, leftover_rec def __transpose_rectangle(rec): ''' Returns a new rectangle that is the transpose of the input: The x and y attributes are switched, as are width and height. The label and color_code attributes are preserved. Input: rec: (Rectangle) Returns: (Rectangle) transpose of rec. ''' return Rectangle((rec.y, rec.x), (rec.height, rec.width), rec.label, rec.color_code) def __compute_row_wide(bounding_rec, row_data, total_sum): ''' Helper function for compute_row. Serves the same purpose as compute_row, but only when the bounding rectangle is at least as wide as it is tall. Inputs: Same as compute_row, except that bounding_rec must have a width greater than or equal to its height. Returns: Same as compute_row. ''' assert bounding_rec.width >= bounding_rec.height row_sum = sum(t.value for t in row_data) row_width = bounding_rec.width * row_sum / total_sum row_layout = [] y = bounding_rec.y for t in row_data: height = bounding_rec.height * t.value / row_sum rec = Rectangle((bounding_rec.x, y), (row_width, height)) if rec.width > 0 and rec.height > 0: row_layout.append((rec, t)) y += height leftover = Rectangle((bounding_rec.x + row_width, bounding_rec.y), (bounding_rec.width - row_width, bounding_rec.height)) return row_layout, leftover
268
5
1
1
피토니
피토니·2023-11-15
문제의 로직을 분석하면, 트리 구조에서 데이터를 가져와 이를 시각적으로 나타내는 데에 초점이 맞추어져 있는 것 같습니다. 특히, 각 단계별로 정렬, 레이아웃 초기화, 행 형성 등의 작업을 거쳐 최종적으로 트리맵을 생성하고 있습니다. 올려주신 코드에서 아래 내용들을 확인할 필요가 있을 것 같습니다. 레이아웃 계산: 트리의 각 노드에 대한 렉탱글의 크기와 ...
뎁스_2599뎁스_2599· 2년

질문이미지 인식의 정확도를 높이고 싶습니다.

안녕하세요, 저는 움직이는 영상에서 특정 물체를 인식하는 코드를 만들고자 합니다. 다만 유튜브와 깃허브에서 나온 자료들을 활용하여 만들었으나 물체를 인식하는데 정확도가 비교적 떨어집니다. 아래의 코드에서 어떻게 정확도를 높일 수 있을까요? 분석하고자 하는 영상은 아래의 링크와 같으며, 떠다니는 구모양의 powder의 갯수를 세는 것이 목적입니다. 참고 영상: https://www.youtube.com/watch?v=BtKI0_jdjE8 import cv2 from tracker import * # create tracker object tracker = EuclideanDistTracker() cap=cv2.VideoCapture(r"C:\Users\Desktop\spyder\yolov8-custom-object-training-tracking-main\yolov8-custom-object-training-tracking-main\surf\surf.mp4") # Object detectino from Stable camera object_detector = cv2.createBackgroundSubtractorMOG2(history = 100, varThreshold = 40) while True: ret, frame = cap.read() height, width, _ = frame.shape # 1. Object Detection mask = object_detector.apply(frame) _, mask = cv2.threshold(mask, 244, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) detections = [] for cnt in contours: # Calculate area and remove small elements area = cv2.contourArea(cnt) if area > 100: # cv2.drawContours(roi, [cnt], -1, (0, 255, 0), 2) x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) detections.append([x, y, w, h]) # 2. Object Tracking boxes_ids = tracker.update(detections) for box_id in boxes_ids: x, y, w, h, id = box_id cv2.putText(frame, str(id), (x, y - 15), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 2) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) cv2.imshow("Frame", frame) cv2.imshow("Mask", mask) key = cv2.waitKey(30) if key == 27: break cap.release() cv2.destroyAllwindows()
527
1
0
피토니
피토니·2023-06-01
몇 가지 방법을 추가로 적용하여 정확도를 높일 수 있습니다. 이미지 전처리 이미지의 노이즈를 제거하거나 contrast를 향상시키는 등의 이미지 전처리 기법을 사용하여 값을 조금씩 조정하면서 물체 검출 성능을 향상시킬 수 있습니다. 예를 들면 다음과 같은 코드가 될 수 있습니다. # 이미지 전처리 # 1. 가우시안 블러로 노이즈 제거 : 가우시안 블러는 ...
뎁스_2599뎁스_2599· 2년

질문딥러닝 코드 도와주세요!!

안녕하세요, 다름이 아니라 코드를 진행 하는 과정 중 궁금한 점 몇가지가 있어 질문드립니다. 아래와 같이 코드를 돌렸을 때 iou 의 값이 0.37778513125965146에서 비슷하거나 오르지가 않는데 혹시 어떻게 하면 올릴 수 있나요? cell의 개수를 세고 싶어 코드를 마지막에 작성했는데, ValueError: buffer is not large enough 오류가 뜹니다. 이 오류의 해결 방법을 알 수 있을까요? 오류 내용: File "C:Users.spyder-py3practice1_051423.py", line 204, in count_cells(prediction_other[test_img_number], t = 65) File "C:Users.spyder-py3practice1_051423.py", line 173, in count_cells plt.imsave('test.png', img_mask) File "C:Usersanaconda3libsite-packagesmatplotlibpyplot.py", line 2165, in imsave return matplotlib.image.imsave(fname, arr, **kwargs) File "C:Usersanaconda3libsite-packagesmatplotlibimage.py", line 1645, in imsave image = PIL.Image.frombuffer( File "C:Usersanaconda3libsite-packagesPILImage.py", line 2893, in frombuffer im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) ValueError: buffer is not large enough 코드: from simple_unet_model import simple_unet_model # Use normal unet model from keras.utils import normalize import os import cv2 from PIL import Image import numpy as np from matplotlib import pyplot as plt image_directory = r"C:UsersDesktopVS Codecell_images" mask_directory = r"C:UsersDesktopVS Codecell_masks" SIZE = 256 image_dataset = [] mask_dataset = [] images = os.listdir(image_directory) for i, image_name in enumerate(images): if (image_name.split('.')[1] == 'png'): image_path = os.path.join(image_directory, image_name) image = cv2.imread(image_path,0) if image is None: print(f"Unable to read image file: {image_path}") continue image = Image.fromarray(image) image = image.resize((SIZE, SIZE)) image_dataset.append(np.array(image)) masks = os.listdir(mask_directory) for i, image_name in enumerate(masks): if (image_name.split('.')[1] == 'png'): image_path = os.path.join(mask_directory, image_name) image = cv2.imread(image_path,0) if image is None: print(f"Unable to read image file: {image_path}") continue image = Image.fromarray(image) image = image.resize((SIZE, SIZE)) mask_dataset.append(np.array(image)) # Normalize images image_dataset = np.expand_dims(normalize(np.array(image_dataset), axis = 1),3) #D not normalize masks, just rescale to 0 to 1. mask_dataset = np.expand_dims((np.array(mask_dataset)),3) /255 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(image_dataset, mask_dataset, test_size = 0.10, random_state = 0) # Sanity check, view few images import random import numpy as np image_number = random.randint(0, len(X_train)) plt.figure(figsize = (12, 6)) plt.subplot(121) plt.imshow(np.reshape(X_train[image_number], (256, 256)), cmap = 'gray') plt.subplot(122) plt.imshow(np.reshape(y_train[image_number], (256, 256)), cmap = 'gray') plt.show() ####################################################################### IMG_HEIGHT = image_dataset.shape[1] IMG_WIDTH = image_dataset.shape[2] IMG_CHANNELS = image_dataset.shape[3] def get_model(): return simple_unet_model(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) model = get_model() # if starting with pre-trained weights. # model.Load_weights('mitochondria_gpu_tf1.4.hdf5) history = model.fit(X_train, y_train, batch_size = 16, verbose = 1, epochs = 50, validation_data = (X_test, y_test), shuffle = False) model.save('cell_test1.hdf5') ########################################################### # Evaluate the model _, accuracy = model.evaluate(X_test, y_test) print("Accuracy = ", (accuracy * 100), "%") # Plot the training and validation accuracy and Loss at each epoch loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'y', label = 'Training loss') plt.plot(epochs, val_loss, 'r', label = 'Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() accuracy = history.history['accuracy'] # acc = accuracy val_accuracy = history.history['val_accuracy'] plt.plot(epochs, accuracy, 'y', label = 'Training acc') plt.plot(epochs, val_accuracy, 'r', label = 'Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() **################################## #IOU y_pred=model.predict(X_test) y_pred_thresholded = y_pred > 0.5 intersection = np.logical_and(y_test, y_pred_thresholded) union = np.logical_or(y_test, y_pred_thresholded) intersection = np.sum(intersection) union = np.sum(union) iou_score = intersection / union print("IoU score is: ", iou_score)** ############################################################## # predict on a few images model.load_weights('cell_test1.hdf5') test_img_number = random.randint(0, len(X_test)) test_img = X_test[test_img_number] ground_truth = y_test[test_img_number] test_img_norm = test_img[:,:,0][:,:,None] test_img_input = np.expand_dims(test_img_norm, 0) prediction = (model.predict(test_img_input)[0,:,:,0] > 0.5).astype(np.uint8) test_img_other = cv2.imread(r"C:UsersDesktopVS Codecell_imagesMar24bS1C2R1_DMl_200x_y.png", 0) test_img_other_norm = np.expand_dims(normalize(np.array(test_img_other), axis = 1), 2) test_img_other_norm = test_img_other_norm[:,:,0][:,:,None] test_img_other_input = np.expand_dims(test_img_other_norm, 0) prediction_other = (model.predict(test_img_other_input)[0,:,:,0] > 0.5).astype(np.uint8) plt.figure(figsize = (16, 8)) plt.subplot(231) plt.title("Testing Image") plt.imshow(test_img[:,:,0], cmap = 'gray') plt.subplot(232) plt.title('Testing Lable') plt.imshow(ground_truth[:,:,], cmap = 'gray') plt.subplot(233) plt.title("Prediction on test image") plt.imshow(prediction, cmap = 'gray') plt.subplot(234) plt.title("External Image") plt.imshow(test_img_other, cmap = 'gray') plt.subplot(235) plt.title('Prediction of external Image') plt.imshow(prediction_other, cmap = 'gray') plt.show() ########################################################################## **# count cells using predicted mask original_img = test_img[test_img_number] img0 = original_img.copy() #img0 = np.asarray(original_img) plt.imshow(img0) plt.show() def count_cells(pred_mask, t = 65): img_mask = np.squeeze(pred_mask) plt.imsave('test.png', img_mask) image = Image.open('test.png').convert("L") img = np.asarray(image) img = img.copy() blur = cv2.GaussianBlur(img, (5, 5), 0) (t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY) # find contours (_, contours, _) = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CAHIN_APPROS_SIMPLE) # create all-black mask image mask = np.zeros(img.shape, dtype = 'uint8') # draw white rectangles for each object's bounding box for c in contours: (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(mask, (x, y), (x + w, y + h), (255, 255, 255), -1) # draw contours over original image cv2.drawContours(img, contours, -1, (255, 100, 100), 1) plt.imshow(img) plt.show() # print table of contours and sizes print("Found {} cells".format(len(contours))) for (i, c) in enumerate(contours): print(" Size of cell {}: {}".format(i, len(c))) return count_cells(prediction_other[test_img_number], t = 65)**
508
3
0
피토니
피토니·2023-05-15
iou 값을 올리는 방법은 몇가지가 있을 수 있습니다. YOLOv4, EfficientDet, RetinaNet 등과 같은 최신 딥러닝 모델을 사용합니다.학습 데이터를 더 많이 생성하여 모델의 일반화 성능을 향상시키는 데이터 확장을 사용합니다. 예를 들어 이미지 회전, 확대/축소, 잘라내기, 뒤집기, 색상 변환 등의 방법을 사용하여 데이터를 확장할 수 있습...
뎁스_2599뎁스_2599· 2년

질문딥러닝 코드 질문

안녕하세요, 현재 딥러닝으로 세포 image segmentaion을 하려고 하는데요. 제가 코드를 돌리면 iou = 0이 뜨고, 아래의 첨부한 그림과 같이 그래프가 뜨질 않습니다. 혹시 어떤 부분을 수정해야할까요? from simple_unet_model import simple_unet_model # Use normal unet model from keras.utils import normalize import os import cv2 from PIL import Image import numpy as np from matplotlib import pyplot as plt image_directory = r"C:\Users\Desktop\VS Code\cell_images" mask_directory = r"C:\Users\Desktop\VS Code\cell_masks" SIZE = 256 image_dataset = [] mask_dataset = [] images = os.listdir(image_directory) for i, image_name in enumerate(images): if (image_name.split('.')[1] == 'png'): image_path = os.path.join(image_directory, image_name) image = cv2.imread(image_path,0) if image is None: print(f"Unable to read image file: {image_path}") continue image = Image.fromarray(image) image = image.resize((SIZE, SIZE)) image_dataset.append(np.array(image)) masks = os.listdir(mask_directory) for i, image_name in enumerate(masks): if (image_name.split('.')[1] == 'png'): image_path = os.path.join(mask_directory, image_name) image = cv2.imread(image_path,0) if image is None: print(f"Unable to read image file: {image_path}") continue image = Image.fromarray(image) image = image.resize((SIZE, SIZE)) mask_dataset.append(np.array(image)) # Normalize images image_dataset = np.expand_dims(normalize(np.array(image_dataset), axis = 1),3) #D not normalize masks, just rescale to 0 to 1. mask_dataset = np.expand_dims((np.array(mask_dataset)),3) /255 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(image_dataset, mask_dataset, test_size = 0.10, random_state = 0) # Sanity check, view few images import random import numpy as np image_number = random.randint(0, len(X_train)) plt.figure(figsize = (12, 6)) plt.subplot(121) plt.imshow(np.reshape(X_train[image_number], (256, 256)), cmap = 'gray') plt.subplot(122) plt.imshow(np.reshape(y_train[image_number], (256, 256)), cmap = 'gray') plt.show() ####################################################################### IMG_HEIGHT = image_dataset.shape[1] IMG_WIDTH = image_dataset.shape[2] IMG_CHANNELS = image_dataset.shape[3] def get_model(): return simple_unet_model(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS) model = get_model() # if starting with pre-trained weights. # model.Load_weights('mitochondria_gpu_tf1.4.hdf5) history = model.fit(X_train, y_train, batch_size = 16, verbose = 1, epochs = 1, validation_data = (X_test, y_test), shuffle = False) model.save('cell_test1.hdf5') ########################################################### # Evaluate the model _, accuracy = model.evaluate(X_test, y_test) print("Accuracy = ", (accuracy * 100.0), "%") # Plot the training and validation accuracy and Loss at each epoch loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(loss) + 1) plt.plot(epochs, loss, 'y', label = 'Training loss') plt.plot(epochs, val_loss, 'r', label = 'Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() accuracy = history.history['accuracy'] # acc = accuracy val_accuracy = history.history['val_accuracy'] plt.plot(epochs, accuracy, 'y', label = 'Training acc') plt.plot(epochs, val_accuracy, 'r', label = 'Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() ################################## #IOU y_pred=model.predict(X_test) y_pred_thresholded = y_pred > 0 intersection = np.logical_and(y_test, y_pred_thresholded) union = np.logical_or(y_test, y_pred_thresholded) iou_score = np.sum(intersection) / np.sum(union) print("IoU socre is: ", iou_score) ############################################################## # predict on a few images model = get_model() test_img_number = random.randint(0, len(X_test)) test_img = X_test[test_img_number] ground_truth = y_test[test_img_number] test_img_norm = test_img[:,:,0][:,:,None] test_img_input = np.expand_dims(test_img_norm, 0) prediction = (model.predict(test_img_input)[0,:,:,0] > 0.2).astype(np.uint8) test_img_other = cv2.imread(r"C:\Users\Desktop\VS Code\cell_images\37_y.png", 0) test_img_other_norm = np.expand_dims(normalize(np.array(test_img_other), axis = 1), 2) test_img_other_norm = test_img_other_norm[:,:,0][:,:,None] test_img_other_input = np.expand_dims(test_img_other_norm, 0) prediction_other = (model.predict(test_img_other_input)[0,:,:,0] > 0.2).astype(np.uint8) plt.figure(figsize = (16, 8)) plt.subplot(231) plt.title("Testing Image") plt.imshow(test_img[:,:,0], cmap = 'gray') plt.subplot(232) plt.title('Testing Lable') plt.imshow(ground_truth[:,:,], cmap = 'gray') plt.subplot(233) plt.title("Prediction on test image") plt.imshow(prediction, cmap = 'gray') plt.subplot(234) plt.title("External Image") plt.imshow(test_img_other, cmap = 'gray') plt.subplot(235) plt.title('Prediction of external Image') plt.imshow(prediction_other, cmap = 'gray') plt.show()
200
3
0
피토니
피토니·2023-05-14
epochs를 1로 설정했기 때문에 학습이 제대로 이루어지지 않았을 수 있습니다. 딥러닝 모델을 학습할 때 epochs를 충분히 설정하여 학습을 시켜야 모델이 세포 이미지를 segmenting하는 것을 잘 학습할 수 있습니다. 10이나 20 정도로 올려보시기 바랍니다. 그리고 IoU를 계산하는 부분에서 np.sum() 함수는 전체 배열의 요소를 합산하기 ...
뎁스_2599뎁스_2599· 2년

질문Segmentation fault

안녕하세요, 현재 R을 배우고 있는 학생입니다. 다름이 아니라 BATCH를 사용할 때 자꾸 segmentation fault가 떠서 질문드립니다. $ R CMD BATCH myfirst_rcode 이렇게 치면 Segmentation fault 이렇게 뜨는데  어떻게 해결할 수 있는지 알 수 있을까요?
218
2
0
피토니
피토니·2023-05-05
먼저 코드를 볼 수 있으면 좋겠지만 코드에 문제가 없다면 Segmentation fault는 주로 메모리 관련 문제입니다. 코드 상에 메모리 누수가 있거나 코드를 실행하려고 설치한 패키지 중에 메모리 문제가 있는 것이 있을 수도 있습니다. 혹은 R을 설치한 컴퓨터나 R을 설치할 때의 문제 있을 수도 있으므로 가능하다면 다른 컴퓨터에서도 실행해보시기 바랍...