{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import math\nimport os\nimport cv2\nimport csv\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom collections import Counter\nfrom glob import glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def viewImage(image, title):\n    cv2.namedWindow(title, cv2.WINDOW_NORMAL)\n    cv2.imshow(title, image)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n\n\ndef recizeImg(image):\n    width = 300\n    height = 300\n    dim = (width, height)\n    resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)\n    print('Resized Dimensions : ', resized.shape)\n    return resized\n\n\ndef get_dominant_color(image, k=4):\n    image = image.reshape((image.shape[0] * image.shape[1], 3))\n    clt = KMeans(n_clusters=k)\n    labels = clt.fit_predict(image)\n    label_counts = Counter(labels)\n    dominant_color = clt.cluster_centers_[label_counts.most_common(1)[0][0]]\n    return list(dominant_color)\n\n\n# circle_val\ndef circle_measure(cnt):\n    denominator = cv2.arcLength(cnt, True) ** 2\n    return math.pi * 4 * cv2.contourArea(cnt) / denominator if denominator != 0 else 0\n\n\n# med area react for results:\ndef med_area_rectangles(little_rects):\n    res_area = 0\n    for ltl_rect in little_rects:\n        x, y, w, h = ltl_rect\n        res_area += w * h\n    return res_area / len(little_rects)\n\n\ndef rect_area(rect):\n    x, y, w, h = rect\n    return w * h\n\n\ndef median_for_contours_shape(cnts):\n    widths, height = 0, 0\n    for cnt in cnts:\n        _, _, w, h = cv2.boundingRect(cnt)\n        widths += w\n        height += h\n    return widths / len(cnts), height / len(cnts)\n\n\ndef resolve_ret(dom_color, lim_yell_color):\n    ret = 175 if abs(dom_color[0] - lim_yell_color[0]) > 6 else 140\n    return ret\n\n\ndef del_little_area_contours(contours):\n    # find med area and del some contours\n    res_area = 0\n    for cnt in contours:\n        res_area += cv2.contourArea(cnt)\n    med_area = res_area / len(contours)\n    ind = 0\n    while ind != len(contours):\n        if cv2.contourArea(contours[ind]) < med_area:\n            del contours[ind]\n        else:\n            ind += 1\n\n\ndef take_circle_measure_in_little_cnts(little_cnts, x, y, w, h, ltl_rectangles):\n    ind = 0\n    while ind != len(little_cnts):\n        if circle_measure(little_cnts[ind]) < 0.3:\n            del little_cnts[ind]\n        else:\n            ltl_rect = x_little, y_little, w_little, h_little = cv2.boundingRect(little_cnts[ind])\n            if ltl_rect != (x, y, w, h):\n                ltl_rectangles.append([x_little + x, y_little + y, w_little, h_little])\n            ind += 1\n\n\ndef del_small_rects_in_little_cnts(ltl_rectangles, img_draw_first):\n    med_area_rects = med_area_rectangles(ltl_rectangles)\n    for rect in ltl_rectangles:\n        if rect_area(rect) <= med_area_rects * 1.5:\n            x_little, y_little, w_little, h_little = rect\n            cv2.rectangle(img_draw_first, (x_little, y_little), (x_little + w_little, y_little + h_little),\n                          (0, 255, 0), 2)\n\n\ndef draw_big_rects_orign(big_rectangles, img):\n    for big_rect in big_rectangles:\n        x, y, w, h = big_rect\n        cv2.rectangle(img, (x, y), (x + w, y + h),\n                      (0, 255, 0), 2)\n\n\ndef try_work_with_every_corn(contours, target):\n    ltl_rectangles = []\n    med_w, med_h = median_for_contours_shape(contours)\n    for cnt in contours:\n        x, y, w, h = cv2.boundingRect(cnt)\n        roi_color = target[y:y + h, x:x + w]\n        roi_color_copy = roi_color.copy()\n        # viewImage(roi_color, title='one contour')\n        if w < med_w and h < med_h:  # if one img shape less then med then skip him\n            continue\n        gray = cv2.cvtColor(roi_color, cv2.COLOR_BGR2GRAY)\n        gray = cv2.GaussianBlur(gray, (3, 3), 0)  # swing effect\n        # viewImage(gray, title='gray one contour')\n        edged = cv2.Canny(gray, 10, 100, L2gradient=True)  # seek contours in gray img(without mask)\n        # viewImage(edged, title='gray one contour with limits')\n        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (6, 6))\n        closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)  # for closing open limits\n        # viewImage(closed, title='morfology')\n        little_cnts = cv2.findContours(closed, cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_L1)[0]\n        cv2.drawContours(roi_color, little_cnts, -1, (0, 0, 255), 1)\n        # viewImage(roi_color, title='small cnts on one cnt')\n\n        # take only circle forms\n        take_circle_measure_in_little_cnts(little_cnts, x, y, w, h, ltl_rectangles)\n\n        big_rectangles.append([x, y, w, h])\n        cv2.drawContours(roi_color_copy, little_cnts, -1, (0, 0, 255), 1)\n        # viewImage(roi_color_copy, title='small cnts on one cnt who have circle')\n    return ltl_rectangles, big_rectangles\n\n\ndef get_big_rectangles(contours):\n    big_rectangles = []\n    for cnt in contours:\n        x, y, w, h = cv2.boundingRect(cnt)\n        big_rectangles.append([x, y, w, h])\n    return big_rectangles\n\n\ndef read_images(path):\n    titles = []\n    images = []\n    count = 0\n    for image_path in glob(os.path.join(path, \"*.jpg\")):\n        titles.append(os.path.basename(image_path)[:-4])\n        image_bgr = cv2.imread(image_path, cv2.IMREAD_COLOR)\n        images.append(image_bgr)\n        count += 1\n    return images, titles","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"img_num = 1\nlim_yell_color = [44.08729689253203, 107.89121749458928, 43.02856063060145]\npath = \"../input/global-wheat-detection/test\"\nimages, titles = read_images(path)\ntitle_index = 0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"title_index = 0\nwith open('submission.csv', mode='tw', newline='') as employee_file:\n    employee_writer = csv.writer(employee_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n    employee_writer.writerow(['image_id', 'PredictionString'])\n\n    for img in images:\n        img_draw_first = img.copy()\n        img_draw_second = img.copy()\n\n        # resize image, maybe use in future\n        # img = recizeImg(img)\n\n        # find dom_color\n        hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n        # dom_color = get_dominant_color(hsv_image)\n        dom_color = lim_yell_color\n\n\n        # print orig and hsv\n        # viewImage(img, title='original(recize)')\n        hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n        # viewImage(hsv_img, title='hsv_img')\n\n        # check yell_hsv\n        yell = np.uint8([[[0, 237, 255]]])\n        yell_hsv = cv2.cvtColor(yell, cv2.COLOR_BGR2HSV)\n        # print('yell_hsv : ', yell_hsv)\n\n        ## getting green HSV color representation\n        yell_low = np.array([20, 0, 100])\n        yell_high = np.array([40, 255, 255])\n        curr_mask = cv2.inRange(hsv_img, yell_low, yell_high)\n        hsv_img[curr_mask > 0] = ([30, 255, 255])\n        # Vizualize the mask\n        # viewImage(curr_mask, title='mask')\n        # viewImage(hsv_img, title='with mask')\n        target = cv2.bitwise_and(img, img, mask=curr_mask)\n        # cv2.imwrite(\"target.png\", target)  # сегментированное изображение\n\n        ## converting the HSV image to Gray inorder to be able to apply\n        ## contouring\n        RGB_again = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)\n        gray = cv2.cvtColor(RGB_again, cv2.COLOR_RGB2GRAY)\n        # viewImage(gray, title='to gray')  ## 3\n        ret = resolve_ret(dom_color, lim_yell_color)\n        ret, threshold = cv2.threshold(gray, ret, 255, 0)  # если изобрыжение слишком темное(после наложенной маски),\n        # то оно закрашивается в черный цвет\n        # viewImage(threshold, title='limit_picture')  ## пороговое изображение, ret - порог\n        contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n        # find med area and del some contours\n        del_little_area_contours(contours)\n        cv2.drawContours(img, contours, -1, (0, 0, 255), 2)\n        # viewImage(img, title='conturs after del little area')\n        # cv2.imwrite(\"just_red_cntrs.png\", img)\n        # viewImage(target, title='conturs on target')\n\n        # work either cnt:\n        big_rectangles = get_big_rectangles(contours)\n\n\n        # del_small_rects_in_little_cnts(ltl_rectangles, img_draw_first)\n        # viewImage(img_draw_first, title='res')\n        draw_big_rects_orign(big_rectangles, img_draw_second)\n        # viewImage(img_draw_second, title='res with rects')\n        # cv2.imwrite(\"img_with_little_rect.png\", img_draw_first)\n        # cv2.imwrite(path + 'results/' + titles[title_index] + \"_big_rect.png\", img_draw_second)\n\n        #save svc\n        title_str = str(titles[title_index])\n        out = \"\"\n        for ind, rect in enumerate(big_rectangles):\n#             if ind > 40:\n#                 break\n            x, y, w, h = map(lambda x: str(x), rect)\n            first_num = str(0.5)\n            out += ' '.join([first_num, x, y, w, h, ' '])\n        employee_writer.writerow([title_str, out])\n        title_index += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}