-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDOC_SCANNER_APP
1 lines (1 loc) · 12.7 KB
/
DOC_SCANNER_APP
1
{"cells":[{"cell_type":"markdown","metadata":{"id":"6iKY_fUJhDe2"},"source":["**Upload your images**"]},{"cell_type":"code","execution_count":43,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":476},"executionInfo":{"elapsed":30291,"status":"ok","timestamp":1666893970639,"user":{"displayName":"Murat Ali","userId":"15885094827832996153"},"user_tz":-180},"id":"LvwMnT3DZl0f","outputId":"19b2dfeb-1f21-4e43-c10c-f08a1ee62fd7"},"outputs":[{"output_type":"stream","name":"stdout","text":["Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n","/content/drive/MyDrive/YOLO_DOC_TEST\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.HTML object>"],"text/html":["\n"," <input type=\"file\" id=\"files-dc40865a-c360-41d0-9086-6b6c5698425b\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-dc40865a-c360-41d0-9086-6b6c5698425b\">\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," </output>\n"," <script>// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) => {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable<!Object>} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) => {\n"," inputElement.addEventListener('change', (e) => {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) => {\n"," cancel.onclick = () => {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) => {\n"," const reader = new FileReader();\n"," reader.onload = (e) => {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position < fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","</script> "]},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Saving photo1666893060.jpeg to photo1666893060.jpeg\n","move photo1666893060.jpeg to upload/photo1666893060.jpeg\n","Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.4, device='', exist_ok=False, img_size=640, iou_thres=0.45, name='exp', no_trace=False, nosave=False, project='/content/drive/MyDrive/YOLO_DOC_TEST/results', save_conf=False, save_txt=False, source='/content/drive/MyDrive/YOLO_DOC_TEST/upload', update=False, view_img=False, weights=['/content/drive/MyDrive/YOLO_DOC_SCANNER/exp/weights/best.pt'])\n","YOLOR 🚀 v0.1-115-g072f76c torch 1.12.1+cu113 CUDA:0 (Tesla T4, 15109.75MB)\n","\n","Fusing layers... \n","RepConv.fuse_repvgg_block\n","RepConv.fuse_repvgg_block\n","RepConv.fuse_repvgg_block\n","IDetect.fuse\n","Model Summary: 314 layers, 36497954 parameters, 6194944 gradients\n"," Convert model to Traced-model... \n"," traced_script_module saved! \n"," model is traced! \n","\n","/usr/local/lib/python3.7/dist-packages/torch/functional.py:478: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ../aten/src/ATen/native/TensorShape.cpp:2894.)\n"," return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]\n","1 papernews, Done. (18.1ms) Inference, (1.7ms) NMS\n"," The image with the result is saved in: /content/drive/MyDrive/YOLO_DOC_TEST/results/exp/photo1666893060.jpeg\n","Done. (0.372s)\n"]}],"source":["from google.colab import drive\n","drive.mount('/content/drive')\n","\n","%cd /content/drive/MyDrive/YOLO_DOC_TEST\n","import os\n","from google.colab import files\n","import shutil\n","\n","upload_folder = 'upload'\n","result_folder = 'results'\n","\n","if os.path.isdir(upload_folder):\n"," shutil.rmtree(upload_folder)\n","if os.path.isdir(result_folder):\n"," shutil.rmtree(result_folder)\n","os.mkdir(upload_folder)\n","os.mkdir(result_folder)\n","\n","uploaded = files.upload()\n","for filename in uploaded.keys():\n"," dst_path = os.path.join(upload_folder, filename)\n"," print(f'move {filename} to {dst_path}')\n"," shutil.move(filename, dst_path)\n","\n","!python detect.py --weights /content/drive/MyDrive/YOLO_DOC_SCANNER/exp/weights/best.pt --conf 0.4 --source /content/drive/MyDrive/YOLO_DOC_TEST/upload\n","\n"]},{"cell_type":"markdown","metadata":{"id":"Tptbcaf_f9x1"},"source":["**See the results**"]},{"cell_type":"code","execution_count":44,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":17},"executionInfo":{"elapsed":914,"status":"ok","timestamp":1666893971541,"user":{"displayName":"Murat Ali","userId":"15885094827832996153"},"user_tz":-180},"id":"zsNS5l3PgAd9","outputId":"d581f04b-f39a-473d-e97a-b534c014f32a"},"outputs":[{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.Javascript object>"],"application/javascript":["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.Javascript object>"],"application/javascript":["download(\"download_0bef61d5-3197-4cd3-9f17-20b852a1e945\", \"out2.jpg\", 1323646)"]},"metadata":{}}],"source":["import cv2\n","import numpy as np\n","import skimage.exposure\n","from google.colab.patches import cv2_imshow\n","img = cv2.imread('/content/drive/MyDrive/YOLO_DOC_TEST/papers/result.jpg') \n","out2 = skimage.exposure.rescale_intensity(img, in_range=(64,192), out_range=(0,255))\n","cv2.imwrite(\"out2.jpg\",out2)\n","from google.colab import files\n","files.download('/content/drive/MyDrive/YOLO_DOC_TEST/out2.jpg')"]}],"metadata":{"accelerator":"GPU","colab":{"collapsed_sections":[],"provenance":[{"file_id":"1jxPfQdpr8MJc4wmYaUl-zubufO--cUlw","timestamp":1666890956335},{"file_id":"1D3Q6QrW1qZgDPjxmMEW5N6qBKtUTUZjL","timestamp":1666437189878},{"file_id":"10mggqp9LFojaHgd5YCDRmOc5L-ESNhIp","timestamp":1666284113739},{"file_id":"1X9A8odmK4k6l26NDviiT6dd6TgR-piOa","timestamp":1666276884975},{"file_id":"1YnbqOinBZV-c9I7fk_UL6acgnnmkXDMM","timestamp":1657587444672},{"file_id":"1gDZ2xcTOgR39tGGs-EZ6i3RTs16wmzZQ","timestamp":1656523193068},{"file_id":"https://github.com/ultralytics/yolov5/blob/master/tutorial.ipynb","timestamp":1591755516488}]},"kernelspec":{"display_name":"Python 3","name":"python3"}},"nbformat":4,"nbformat_minor":0}