{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"},{"sourceId":1173763,"sourceType":"datasetVersion","datasetId":666084}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport cv2\nimport sys\nimport os.path\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-05T07:27:20.150603Z","iopub.execute_input":"2024-01-05T07:27:20.151021Z","iopub.status.idle":"2024-01-05T07:27:20.619032Z","shell.execute_reply.started":"2024-01-05T07:27:20.150990Z","shell.execute_reply":"2024-01-05T07:27:20.617504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\npath = '/kaggle/input/global-wheat-detection'\nsys.path.append(path)\nprint(path)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:04.643785Z","iopub.execute_input":"2024-01-05T07:26:04.644339Z","iopub.status.idle":"2024-01-05T07:26:04.651301Z","shell.execute_reply.started":"2024-01-05T07:26:04.644299Z","shell.execute_reply":"2024-01-05T07:26:04.650310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confThreshold = 0.4  #置信度阈值\nnmsThreshold = 0.4   #非极大值抑制阈值\ncfg_file =f'/kaggle/input/global-wheat-detection-yolo-weights/wheat_detection_tiny.cfg'  \nweight_file = f'/kaggle/input/global-wheat-detection-yolo-weights/wheat_detection_tiny_last.weights' ","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:05.916411Z","iopub.execute_input":"2024-01-05T07:26:05.916946Z","iopub.status.idle":"2024-01-05T07:26:05.922886Z","shell.execute_reply.started":"2024-01-05T07:26:05.916905Z","shell.execute_reply":"2024-01-05T07:26:05.921750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = open(f'/kaggle/input/global-wheat-detection-yolo-weights/obj.names').read().strip().split('\\n')\nprint(classes)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:06.823681Z","iopub.execute_input":"2024-01-05T07:26:06.824077Z","iopub.status.idle":"2024-01-05T07:26:06.839237Z","shell.execute_reply.started":"2024-01-05T07:26:06.824046Z","shell.execute_reply":"2024-01-05T07:26:06.837909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"net = cv2.dnn.readNetFromDarknet(cfg_file, weight_file) #加载YOLOv4预训练模型\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\ndef getOutputsNames(net):\n    layersNames = net.getLayerNames()\n    outputLayerNames = [layersNames[i - 1] for i in net.getUnconnectedOutLayers()]\n    return layersNames, outputLayerNames\nlayersNames, outputLayerNames = getOutputsNames(net)\nprint('YOLOv4各层名称：{0}'.format(layersNames))\nprint('\\nYOLOv4输出层名称：{0}'.format(outputLayerNames))","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:07.528019Z","iopub.execute_input":"2024-01-05T07:26:07.528454Z","iopub.status.idle":"2024-01-05T07:26:08.104751Z","shell.execute_reply.started":"2024-01-05T07:26:07.528421Z","shell.execute_reply":"2024-01-05T07:26:08.103181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def drawPred(classId, conf, left, top, right, bottom, frame):\n    # 绘制Bounding Box\n    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 250), 3)\n\n    label = '%.2f' % conf\n\n    if classes:\n        assert(classId < len(classes))\n        label = '%s:%s' % (classes[classId], label)\n    labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n    top = max(top, labelSize[1])\n    cv2.rectangle(frame, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine), (255, 255, 255), cv2.FILLED)\n    cv2.putText(frame, label, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,0,0), 1)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:08.457015Z","iopub.execute_input":"2024-01-05T07:26:08.457415Z","iopub.status.idle":"2024-01-05T07:26:08.468807Z","shell.execute_reply.started":"2024-01-05T07:26:08.457381Z","shell.execute_reply":"2024-01-05T07:26:08.467517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def postprocess(frame, outp):\n    frameHeight = frame.shape[0]\n    frameWidth = frame.shape[1]\n    pred_str = ''\n    classIds = []\n    confidences = []\n    boxes = []\n    for out in outp:\n        for detection in out:\n            scores = detection[5:]\n            classId = np.argmax(scores)\n            confidence = scores[classId]\n            if confidence > confThreshold:\n                center_x = int(detection[0] * frameWidth)\n                center_y = int(detection[1] * frameHeight)\n                width = int(detection[2] * frameWidth)\n                height = int(detection[3] * frameHeight)\n                left = int(center_x - width / 2)\n                top = int(center_y - height / 2)\n                classIds.append(classId)\n                confidences.append(float(confidence))\n                boxes.append([left, top, width, height])\n\n    indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)\n    if len(indices) > 0:\n        for i in indices:\n            box = boxes[i]\n            left = box[0]\n            top = box[1]\n            width = box[2]\n            height = box[3]\n            drawPred(classIds[i], confidences[i], left, top, left + width, top + height, frame)\n        \n            pred = '{} {} {} {} {} '.format(np.round(confidences[i],1),left,top,width,height)\n            pred_str = pred_str + pred    \n    \n    sub.loc[image_id,'PredictionString'] = pred_str[:-1]\n      \n    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)\n    plt.subplot(2,5,image_id+1)\n    plt.imshow(frame)\n   \n    plt.axis('off')        ","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:10.040801Z","iopub.execute_input":"2024-01-05T07:26:10.041620Z","iopub.status.idle":"2024-01-05T07:26:10.060019Z","shell.execute_reply.started":"2024-01-05T07:26:10.041569Z","shell.execute_reply":"2024-01-05T07:26:10.058175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def yolov4_detect_image(filePath,dispalyFlag = True):\n    outputFile = ''\n    # 打开图像文件\n    if not os.path.isfile(filePath):\n        print(\"图像文件：\", filePath, \" 不存在！\")\n        sys.exit(1)\n    img = cv2.imread(filePath)\n    outputFile = filePath[:-4]+'_YOLOv4_output.jpg'\n\n    blob = cv2.dnn.blobFromImage(img, 1/255, (416,416), [0,0,0], 1, crop=False)\n\n    net.setInput(blob)\n\n    layersNames, outputLayerNames = getOutputsNames(net)\n    outp = net.forward(outputLayerNames)\n\n    postprocess(img, outp)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:11.209697Z","iopub.execute_input":"2024-01-05T07:26:11.210165Z","iopub.status.idle":"2024-01-05T07:26:11.218339Z","shell.execute_reply.started":"2024-01-05T07:26:11.210129Z","shell.execute_reply":"2024-01-05T07:26:11.217230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = '/kaggle/input/global-wheat-detection/test/'\ntest_img_list = os.listdir(test)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:41.195234Z","iopub.execute_input":"2024-01-05T07:26:41.195755Z","iopub.status.idle":"2024-01-05T07:26:41.209958Z","shell.execute_reply.started":"2024-01-05T07:26:41.195716Z","shell.execute_reply":"2024-01-05T07:26:41.208349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(24,15))\nfor i,image in enumerate(test_img_list):\n    img = cv2.imread(test + image)\n    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n    plt.subplot(2,5,i+1)\n    plt.imshow(img)\n    plt.title(image[:-5])\n    plt.axis('off')\n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:26:42.278290Z","iopub.execute_input":"2024-01-05T07:26:42.278796Z","iopub.status.idle":"2024-01-05T07:26:46.025482Z","shell.execute_reply.started":"2024-01-05T07:26:42.278751Z","shell.execute_reply":"2024-01-05T07:26:46.024268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/global-wheat-detection/sample_submission.csv')\nsub","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:27:24.474040Z","iopub.execute_input":"2024-01-05T07:27:24.474945Z","iopub.status.idle":"2024-01-05T07:27:24.514124Z","shell.execute_reply.started":"2024-01-05T07:27:24.474891Z","shell.execute_reply":"2024-01-05T07:27:24.512716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(20,15))\nfor image_id in range(len(sub)):\n    image = test + sub.loc[image_id,'image_id'] + '.jpg'\n    yolov4_detect_image(image, True)\n    plt.title(sub.loc[image_id,'image_id'])\nplt.show()  ","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:27:25.506170Z","iopub.execute_input":"2024-01-05T07:27:25.506626Z","iopub.status.idle":"2024-01-05T07:27:30.162546Z","shell.execute_reply.started":"2024-01-05T07:27:25.506592Z","shell.execute_reply":"2024-01-05T07:27:30.160954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:27:30.165169Z","iopub.execute_input":"2024-01-05T07:27:30.165786Z","iopub.status.idle":"2024-01-05T07:27:30.182208Z","shell.execute_reply.started":"2024-01-05T07:27:30.165745Z","shell.execute_reply":"2024-01-05T07:27:30.180662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-05T07:27:32.065072Z","iopub.execute_input":"2024-01-05T07:27:32.065585Z","iopub.status.idle":"2024-01-05T07:27:32.077057Z","shell.execute_reply.started":"2024-01-05T07:27:32.065546Z","shell.execute_reply":"2024-01-05T07:27:32.075430Z"},"trusted":true},"execution_count":null,"outputs":[]}]}