{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Requirements\n", "\n", "You need python 3 with the following libraries in your environment\n", "* opencv > 3.x (with numpy but it should be provided with it)\n", "* tqdm\n", "* Rtree" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Load decap image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "import cv2\n", "import numpy as np\n", "import math\n", "import pickle\n", "from tqdm.notebook import tqdm\n", "\n", "# ignoring overflow errors (happens in sigmoid manipulations on floats)\n", "_ = np.seterr(over=\"ignore\")\n", "\n", "die_gray = cv2.imread(\"../../93646B/dl-decap/capcom_dl-1927_mz_mit20x.jpg\", 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Load schematics data (if available)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import re \n", "import os\n", "\n", "REFERENCES = dict()\n", "IO_PINS = dict()\n", "FORCE_CELLS = dict()\n", "\n", "main_schematics = \"../DL-1927/DL-1927.sch\"\n", "pinout = \"../DL-1927/pinout.txt\"\n", "force_cells = \"../DL-1927/force-cells.txt\"\n", "\n", "def do_search_references(f):\n", " dir_name = os.path.dirname(f)\n", " print(f)\n", " last_model = None\n", " for line in open(f).read().split(\"\\n\"):\n", " search = re.search(\".*F1 \\\"(.*)\\\".*\", line)\n", " if search:\n", " new_file = search.group(1)\n", " yield from do_search_references(dir_name+os.path.sep+new_file)\n", " continue\n", " search = re.search(\"^L CG24-cells:(.*) .*$\", line)\n", " if search:\n", " last_model = search.group(1)\n", " continue\n", " search = re.search(\"F 0 \\\"(.*)\\\".*\", line)\n", " if search and search.group(1)[0] == \"U\":\n", " yield search.group(1), last_model\n", "\n", "import csv\n", "def load_io(f):\n", " result = dict()\n", " for r in csv.DictReader(open(f), delimiter=\"\\t\"):\n", " if r[\"In Cell\"]:\n", " result[r[\"In Cell\"]] = r[\"Pin\"], r[\"Type\"], r[\"Name\"], \"In\"\n", " if r[\"Out Cell\"]:\n", " result[r[\"Out Cell\"]] = r[\"Pin\"], r[\"Type\"], r[\"Name\"], \"Out\"\n", " return result\n", "\n", "\n", "def load_data():\n", " global IO_PINS, FORCE_CELLS, REFERENCES\n", " try:\n", " IO_PINS = load_io(pinout)\n", " print(\"Loaded IO_PINS data\")\n", " except:\n", " pass\n", " try:\n", " FORCE_CELLS = {re.split(\"\\\\s+\", r)[0]: re.split(\"\\\\s+\", r)[1] for r in open(force_cells).read().split(\"\\n\") if r}\n", " print(\"Loaded FORCE_CELLS data\")\n", " except:\n", " pass\n", " try:\n", " REFERENCES = dict(do_search_references(main_schematics)) \n", " print(\"Loaded REFERENCES data\")\n", " except:\n", " pass\n", "\n", "load_data()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Adjust tilt to have a straight image" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def rotateImage(image, angle):\n", " image_center = tuple(np.array(image.shape[1::-1]) / 2)\n", " rot_mat = cv2.getRotationMatrix2D((0,0), angle, 1.0)\n", " result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n", " return result\n", "\n", "tst = die_gray\n", "# adjust angle\n", "tst = rotateImage(die_gray, -0.07)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Adjust grid size for cells coordinates" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# This needs adjustment on every die\n", "# This is very CG24 oriented and not really useful\n", "unit_size = (12, 13.685)\n", "separator_offset = (117.5, 13.5)\n", "grid_start = (2416, 2302)\n", "\n", "# This is the most important: define a column_size and row_size to convert coordinates into a gate array grid coordinate\n", "column_size = ((unit_size[0]*30+5+separator_offset[0])/2)\n", "row_size = (unit_size[1]*4)\n", "def to_ref_xy(x, y):\n", " return (round((x-grid_start[0])/column_size),round((y-grid_start[1]-5)/row_size))\n", "\n", "def to_ref(x, y):\n", " return \"U%dR%d\" % to_ref_xy(x, y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "offset = (2278+1000, 2260)\n", "size = (1500, 1500)\n", "DISPLAY_CELLS = []\n", "SCALE = 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Viewer\n", "\n", "Look for controls in the comments!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ENABLE_GRID = False\n", "DISPLAY_OVERLAY = True\n", "mouse_position = [0, 0]\n", "pan_position = None\n", "pan_starting_offset = None\n", "pan_rendered = None\n", "COLORS = [\n", " (228,26,28),\n", " (55,126,184),\n", " (77,175,74),\n", " (152,78,163),\n", " (255,127,0),\n", " (255,255,51),\n", " (166,86,40),\n", " (247,129,191)\n", "]\n", "\n", "last_rendered = None\n", "def render(ignore_overlay=False):\n", " global last_rendered\n", " subimg = tst[offset[1]:offset[1]+int(size[1]/SCALE), offset[0]:offset[0]+int(size[0]/SCALE)]\n", " \n", " # Uncomment to test your norm function\n", " #if not ignore_overlay:\n", " #\n", " # subimg = subimg.copy()\n", " # subimg = norm(subimg)\n", " \n", " subimg = cv2.cvtColor(subimg, cv2.COLOR_GRAY2BGR)\n", " off = grid_start[0]\n", " bound_y, bound_x, _ = subimg.shape\n", " \n", " # font \n", " font = cv2.FONT_HERSHEY_SIMPLEX \n", " # fontScale \n", " fontScale = 1\n", " # Blue color in BGR \n", " color = (255, 0, 0)\n", " color_error = (0, 0, 255)\n", " color_black = (0, 0, 0)\n", " color_white = (255, 255, 255)\n", " color_gray = (50,50,50) #(255, 255, 255)\n", " color_grid = color\n", " \n", " # Display grid to check alignment\n", " if ENABLE_GRID and not ignore_overlay:\n", " for i in range(0, 30*23):\n", " x = int(off)\n", "\n", " off += unit_size[0]\n", " if i % 30 == 29:\n", " off += separator_offset[0]\n", " elif i % 15 == 14:\n", " off += 5\n", " else:\n", " x2 = int(off)\n", " if x < offset[0]:\n", " continue\n", " if x2 > (offset[0]+size[0]):\n", " continue\n", " y_off = grid_start[1]+max(0, ((offset[1]-grid_start[1])//unit_size[1]))*unit_size[1]\n", " for i in range(0, int(size[1]//unit_size[1]+1)):\n", " y = int(y_off)\n", "\n", " #if i % 4 == 3:\n", " # off += separator_offset[1]\n", " #elif i % 2 == 1:\n", " # off += 9\n", " #else:\n", " y_off += unit_size[1]\n", " y2 = int(y_off)\n", " #print(x-offset[0], x2-offset[0], y-offset[1], y2-offset[1])\n", " cv2.line(subimg, (x-offset[0], y-offset[1]), (x2-offset[0], y - offset[1]), color_grid, 1)\n", " cv2.line(subimg, (x-offset[0], y-offset[1]), (x-offset[0], y2 - offset[1]), color_grid, 1)\n", " cv2.line(subimg, (x-offset[0], y2-offset[1]), (x2-offset[0], y2 - offset[1]), color_grid, 1)\n", " cv2.line(subimg, (x2-offset[0], y-offset[1]), (x2-offset[0], y2 - offset[1]), color_grid, 1)\n", " \n", " # Line thickness of 2 px \n", " thickness = 2\n", " if DISPLAY_OVERLAY and not ignore_overlay:\n", " # Display cells rectangles\n", " rect_overlay = subimg.copy()\n", " for x, y, w, h, pattern, rects, score, bc_x, bc_y in DISPLAY_CELLS:\n", " c_x, c_y = (rects[0][0]-offset[0], rects[0][1]-offset[1])\n", " \n", " if (c_x < -50 or c_x > bound_x) and (c_y < -50 or c_y > bound_y):\n", " continue\n", " \n", " for r in rects:\n", " cv2.rectangle(rect_overlay, (r[0]-offset[0], r[1]-offset[1]), (r[2]-offset[0], r[1]+max(r[3]-r[1], 55)-offset[1]), COLORS[patterns_idx[pattern] % len(COLORS)], cv2.FILLED)\n", " \n", " # alpha integration of the cells\n", " alpha = 0.4\n", " subimg = cv2.addWeighted(rect_overlay, alpha, subimg,1-alpha, gamma=0)\n", " \n", " # Display pin numbers\n", " for pin in range(0, 30):\n", " c_x, c_y = (2050+20-offset[0], +40+2300-offset[1] + 287*pin)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(pin+1), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (10810-offset[0], +40+2300-offset[1] + 287*pin)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(90-pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (2250+20-offset[0] + 288*pin, +40+ 2100-offset[1])\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(120-pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (2250+20-offset[0] + 288*pin, 10860-offset[1])\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(31+pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", "\n", " # Display cells text\n", " for x, y, w, h, pattern, rects, score, bc_x, bc_y in DISPLAY_CELLS:\n", " textX = (x-offset[0]) + 5 \n", " textY = (y-offset[1]) + 5\n", " \n", " if (textX < -50 or textX > bound_x) and (textY < -50 or textY > bound_y):\n", " continue\n", " \n", " ref = to_ref(x, y)\n", " \n", " textsize = cv2.getTextSize(pattern, font, fontScale, thickness)[0]\n", " textY += textsize[1]\n", " if ref in REFERENCES:\n", " color_txt = color if pattern.replace(\".flip\", \"\") == REFERENCES[ref] else color_error\n", " else:\n", " color_txt = color_white if ref not in REFERENCES else color\n", " cv2.putText(subimg, pattern, (textX, textY), font, fontScale, color_txt, thickness, cv2.LINE_AA)\n", " cv2.putText(subimg, \"[%s]\" % ref, (textX, textY+textsize[1]+2), font, fontScale*0.5, color_txt, 1, cv2.LINE_AA)\n", " if ref in IO_PINS:\n", " cv2.putText(subimg, \"P%s - %s\" % (IO_PINS[ref][0],IO_PINS[ref][2]), (textX, textY+textsize[1]*2+2), font, fontScale*0.5, color_txt, 1, cv2.LINE_AA)\n", "\n", " if SCALE < 0.99 or SCALE > 1.01:\n", " last_rendered = cv2.resize(subimg, (math.ceil(subimg.shape[0]*SCALE), math.ceil(subimg.shape[1]*SCALE)))\n", " else:\n", " last_rendered = subimg\n", " return last_rendered\n", "\n", "###\n", "# Click handler:\n", "###\n", "# Scroll wheel: zoom\n", "# Right click: pan\n", "# Left click: print weak detections\n", "def click(event, x, y, flags, param):\n", " global SCALE, offset, bidule, mouse_position, pan_position, pan_starting_offset, pan_rendered\n", " \n", " if event == cv2.EVENT_MOUSEMOVE:\n", " mouse_position[0], mouse_position[1] = x, y\n", " if pan_position is not None:\n", " sx, sy = pan_position[0] - x, pan_position[1] - y\n", " offset = (pan_starting_offset[0]+int(sx/SCALE), pan_starting_offset[1]+int(sy/SCALE))\n", " rendered = render(True)\n", " rendered[max(-sy, 0):(size[1]+min(-sy, 0)), max(-sx, 0):(size[0]+min(-sx, 0))] = \\\n", " pan_rendered[max(sy, 0):(size[1]+min(sy, 0)), max(sx, 0):(size[0]+min(sx, 0))]\n", " cv2.imshow(\"viewer\", rendered)\n", " pass\n", " return\n", " if event == cv2.EVENT_RBUTTONDOWN:\n", " pan_position = x, y\n", " pan_starting_offset = tuple(offset)\n", " pan_rendered = last_rendered\n", " return\n", " if event == cv2.EVENT_RBUTTONUP:\n", " pan_position = None\n", " cv2.imshow(\"viewer\", render())\n", " return\n", " if event == cv2.EVENT_MOUSEWHEEL:\n", " wheel = flags >> 16\n", " if wheel > 0:\n", " SCALE *= 1.25\n", " offset = (offset[0]+int(mouse_position[0]*0.25/SCALE), offset[1]+int(mouse_position[1]*0.25/SCALE))\n", " else:\n", " offset = (offset[0]-int(mouse_position[0]*0.25/SCALE), offset[1]-int(mouse_position[1]*0.25/SCALE))\n", " SCALE /= 1.25\n", " \n", " cv2.imshow(\"viewer\", render())\n", " return\n", " if event != 1:\n", " return\n", " print(\"ref: %s, x: %d, y: %d, event: %d\" % (to_ref(x+offset[0], y+offset[1]), x+offset[0], y+offset[1], event))\n", " try:\n", " if ENABLE_GRID:\n", " x1, x2, y1, y2 = blocs[x+offset[0]][y+offset[1]]\n", " subimg = tst[y1:y2+6, x1:x2+6]\n", " bidule = subimg\n", " n = 20\n", " #counts, bins = \n", " print(np.histogram(subimg, bins=np.arange(0,1+1/n,1/n)*255)[0])\n", " #plt.hist(bins[:-1], bins, weights=counts)\n", " blocs = total_idx.intersection([x+offset[0], y+offset[1], x+1+offset[0], y+1+offset[1]])\n", " for template_name, score in sorted((total_cells[b] for b in blocs), key=lambda _:_[1]):\n", " print(template_name, score, sep=\"\\t\")\n", " except:\n", " print(\"None\")\n", "\n", "cv2.namedWindow(\"viewer\")\n", "cv2.setMouseCallback(\"viewer\", click)\n", "\n", "############\n", "## Keyboard controls\n", "############\n", "LEFT = 97 # A\n", "RIGHT = 100 # D\n", "DOWN = 115 # S\n", "UP = 119 # W\n", "OVERLAY = 108 # L\n", "ZOOM_IN = 43 # +\n", "ZOOM_OUT = 45 # -\n", "ZOOM_RESET = 48 # 0\n", "RELOAD_DATA = 13 # Enter\n", "CLOSE = 32 # Space\n", "\n", "while True:\n", " cv2.imshow(\"viewer\", render())\n", " k = cv2.waitKey(0)\n", " if k == LEFT:\n", " offset = (offset[0] - int(100/SCALE), offset[1])\n", " elif k == RIGHT:\n", " offset = (offset[0] + int(100/SCALE), offset[1])\n", " elif k == UP:\n", " offset = (offset[0], offset[1] - int(100/SCALE))\n", " elif k == DOWN:\n", " offset = (offset[0], offset[1] + int(100/SCALE))\n", " elif k == OVERLAY:\n", " DISPLAY_OVERLAY = not DISPLAY_OVERLAY\n", " elif k == 43:\n", " SCALE *= 1.25\n", " offset = (offset[0]+int(mouse_position[0]*0.25/SCALE), offset[1]+int(mouse_position[1]*0.25/SCALE))\n", " elif k == 45:\n", " offset = (offset[0]-int(mouse_position[0]*0.25/SCALE), offset[1]-int(mouse_position[1]*0.25/SCALE))\n", " SCALE /= 1.25\n", " elif k == 48:\n", " SCALE = 1\n", " elif k == 13:\n", " # reload\n", " load_data()\n", " elif k == 32:\n", " break\n", " else:\n", " print(\"Unknown key\", k)\n", "\n", "cv2.destroyAllWindows()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Separate destroy in case of crashes\n", "cv2.destroyAllWindows()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Pattern detection" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Cache management\n", "CACHE_PATH = \"./matching-cache-dl-1927.pkl\"\n", "try:\n", " matching_cache = pickle.load(open(CACHE_PATH, \"rb\"))\n", "except Exception as e:\n", " matching_cache = dict()\n", " print(\"Warning: no cache loaded\", str(e))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Norm function applied to all images\n", "def norm(x):\n", " return x\n", " #return (255 / (1 + np.exp(-0.06 * (x.astype(np.float16) - 150)))).astype(np.uint8)\n", "\n", "# tst2 contains the large image\n", "tst2 = norm(tst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load patterns" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "patterns = []\n", "patterns_idx = dict()\n", "template_dir = '../DL-1927/zoo'\n", "\n", "# This will produce \"patterns\" with the following structure\n", "# [(name, img, corner_position, corner_top_x, corner_top_y, bc_size_x, bc_size_y)]\n", "# \"patterns_idx\" is just a dict name -> pattern\n", "# Each pattern has a \".flip\" version with its flipped version\n", "# The corner_ part describe the location of the empty corner (if the total BC size is 3 for instance)\n", "\n", "for n, template_file in enumerate(os.listdir(template_dir)):\n", " if \"test\" in template_file or \"doc\" in template_file:\n", " continue\n", " name = template_file[:-4] # remove .png\n", " img = cv2.imread(template_dir+'/' + template_file, 0)\n", " first_row, last_col = img[0], img[:, -1]\n", " top_x, top_y = np.where(first_row >= 10)[0][-1]+1, np.where(last_col >= 10)[0][0]+1\n", " bc_x, bc_y = round((img.shape[0]+17)/row_size), (img.shape[1]//(column_size / 2))\n", " print(template_file, img.shape, \"%dx%d\" % (bc_x, bc_y))\n", " patterns.append((name, img, \"TOP_RIGHT\", top_x, top_y, bc_x, bc_y))\n", " patterns_idx[name] = n\n", " patterns.append((name+\".flip\", cv2.flip(img, -1), \"BOTTOM_LEFT\", top_x, top_y, bc_x, bc_y))\n", " patterns_idx[name+\".flip\"] = n\n", "\n", "print(\"Loaded %d files\" % (len(patterns) // 2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Perform the matching" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def k_largest_index_argpartition(a, k):\n", " # hack to find the top-k in k*linear time instead of argsort\n", " idx = np.argpartition(a.ravel(),k)[:k]\n", " return np.column_stack(np.unravel_index(idx, a.shape))\n", "\n", "def do_matching(p, hay=tst2, cache=True):\n", " # Get the cache\n", " global matching_cache\n", " name, img, corner, tx, ty, bc_x, bc_y = p\n", " if cache and name in matching_cache:\n", " return matching_cache[name]\n", " mask = img > 10\n", " # detection\n", " res = cv2.matchTemplate(hay, norm(img), cv2.TM_SQDIFF, mask=mask.astype(np.uint8))\n", " # get best 1500 matches\n", " loc = k_largest_index_argpartition(res, 1500)\n", " # create the final structure\n", " match = list(((pt[1], pt[0]), res[tuple(pt)]/mask.sum()) for pt in loc)\n", " if cache:\n", " matching_cache[name] = match\n", " return match\n", "\n", "# Compute all matches\n", "found_patterns = list(tqdm((do_matching(p, hay=tst2) for p in patterns), total=len(patterns)))\n", "\n", "# Found patterns has the following structure\n", "# [\n", "# [((x,y), score), ...], # pattern 0\n", "# [((x,y), score), ...], # pattern 1\n", "# ]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dump the maching cache\n", "pickle.dump(matching_cache, open(CACHE_PATH, \"wb\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matches merger" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from rtree import index as rtree\n", "import math\n", "\n", "def generate_rects(x, y, w, h, corner, tx, ty):\n", " if ty < 10 or tx >= (w-10):\n", " return [(x, y, x+w, y+h)]\n", " if corner == \"TOP_RIGHT\":\n", " return [(x, y, x+tx, y+ty), (x, y+ty, x+w, y+h)]\n", " if corner == \"TOP_LEFT\":\n", " return [(x+(w-tx), y, x+w, y+ty), (x, y+ty, x+w, y+h)]\n", " if corner == \"BOTTOM_LEFT\":\n", " return [(x, y, x+w, y+(h-ty)), (x+(w-tx), y+(h-ty), x+w, y+h)]\n", " if corner == \"BOTTOM_RIGHT\":\n", " return [(x, y, x+w, y+(h-ty)), (x, y+(h-ty), x+tx, y+h)]\n", " raise Exception(\"Unknown corner value %s\" % corner)\n", "\n", "cells = dict()\n", "i = 0\n", "idx = rtree.Index()\n", "total_idx = rtree.Index()\n", "total_cells = dict()\n", "cell_id = 0\n", "for (template_name, template, corner, tx, ty, bc_x, bc_y), loc in zip(patterns, found_patterns):\n", " # Threshold tuning\n", " threshold = 0.027 if bc_x * bc_y < 4 else 0.031\n", " \n", " cell_name = template_name[:-5] if template_name.endswith(\".flip\") else template_name\n", " w, h = template.shape[::-1]\n", " filtered_loc = []\n", " for pt, score in sorted([l for l in loc if l[1] <= 0.04], key=lambda x: x[1]):\n", " # Avoid multiple matches around the same position\n", " rects = generate_rects(pt[0], pt[1], w, h, corner, tx, ty)\n", " intersec = {total_cells[c][0] for r in rects for c in total_idx.intersection(r)}\n", " if template_name in intersec:\n", " continue\n", " cell_id += 1\n", " total_cells[cell_id] = (template_name, score)\n", " cell_ref = to_ref(pt[0], pt[1])\n", " if cell_ref in FORCE_CELLS:\n", " score *= 0 if FORCE_CELLS[cell_ref] == cell_name else 100\n", " if score <= threshold:\n", " filtered_loc.append((pt, score))\n", " for r in rects:\n", " total_idx.insert(cell_id, r)\n", "\n", " if \".flip\" not in template_name:\n", " print(template_name, len(loc), bc_x, bc_y)\n", " if len(loc) > 1500:\n", " print(\"Too many!\")\n", " continue\n", " added = 0\n", " for pt, score in sorted(filtered_loc, key=lambda x: x[1]):\n", " # Avoid multiple matches around the same position\n", " i += 1\n", " if bc_y == 1:\n", " grid_x, grid_y = to_ref_xy(pt[0], pt[1])\n", " if \"flip\" in template_name and grid_x % 2 == 0:\n", " continue\n", " if \"flip\" not in template_name and grid_x % 2 == 1:\n", " continue\n", " rects = generate_rects(pt[0], pt[1], w, h, corner, tx, ty)\n", " intersec = {c//2 for r in rects for c in idx.intersection(r)}\n", " biggest_intersect = max((cells[c][7]*cells[c][8] for c in intersec), default=None)\n", " best_match_rate = min((cells[c][6] for c in intersec if cells[c][7]*cells[c][8] == bc_x*bc_y), default=None)\n", " if not intersec or biggest_intersect < bc_x*bc_y or (biggest_intersect == bc_x*bc_y and score < best_match_rate):\n", " # Accept this cell iff\n", " # * It intersects with no one\n", " # * It intersects with only significantly smaller cells\n", " # * It intersects with only similar pattern but a better match rate\n", " for c in intersec:\n", " cell = cells[c]\n", " #print(\"\\tRemoving cell %d\" % c)\n", " old_rects = cell[5]\n", " for k, r in enumerate(old_rects):\n", " idx.delete(c*2+k, r)\n", " del cells[c]\n", " added += 1\n", " for k, r in enumerate(rects):\n", " idx.insert(i*2+k, r)\n", " cells[i] = (pt[0], pt[1], w, h, template_name, rects, score, bc_x, bc_y)\n", "\n", " print(\"\\tFound it in %d places\" % added)\n", " i += 1\n", "\n", "DISPLAY_CELLS = list(cells.values())\n", "# DISPLAY_CELLS have the following structure\n", "# [\n", "# (x, y, width, height, template_name, rectangles, score, bc_size_x, bc_size_y)\n", "# ]\n", "#\n", "# Additionally, you have:\n", "# * total_cells (dict cell_id->(template_name, score))\n", "# * total_idx (rtree -> cell_id)\n", "# With a weaker threshold to explore false negative by clicking on the viewer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The cells are now detected!\n", "\n", "Reload the viewer and you should see the cells displayed.\n", "\n", "Below are a bunch of additional tools" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Schematics generation\n", "\n", "This is to generate a simple Kicad schematic with all the gates already written down. It's very useful for IO pins where I put all hierarchical labels and pins." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import time\n", "\n", "GUID_SEED = int(time.time())\n", "\n", "def createId():\n", " global GUID_SEED\n", " guid = format(int(GUID_SEED),'x')\n", " GUID_SEED += 1\n", " return guid\n", "\n", "def component(type_, value, ref, guid, xPos, yPos, footprint = str(), matrix = [1,0,0,-1]):\n", " comp = '$Comp\\n'\n", " comp += 'L {} {}\\n'.format(type_, ref)\n", " comp += 'U 1 1 {}\\n'.format(guid)\n", " comp += 'P {:.0f} {:.0f}\\n'.format(xPos, yPos)\n", " comp += 'F 0 \"{}\" H {:.0f} {:.0f} 50 0000 C CNN\\n'.format(ref, xPos, yPos+317)\n", " comp += 'F 1 \"{}\" H {:.0f} {:.0f} 50 0000 C CNN\\n'.format(value, xPos, yPos+226)\n", " comp += 'F 2 \"{}\" H {:.0f} {:.0f} 50 0001 C CNN\\n'.format(footprint, xPos, yPos)\n", " comp += 'F 3 \"\" H {:.0f} {:.0f} 50 0001 C CNN\\n'.format(xPos, yPos)\n", " comp += '\\t1 {:.0f} {:.0f}\\n'.format(xPos, yPos)\n", " comp += '\\t{} {} {} {}\\n'.format(*matrix)\n", " comp += '$EndComp\\n'\n", " return comp\n", "\n", "def textBlock(text, posX, posY, vertical = 0, dimension = 180):\n", " return 'Text Notes {:.0f} {:.0f} {:.0f} {:.0f} ~ 24\\n{}\\n'.format(posX, posY, vertical, dimension, text)\n", "\n", "\n", "global_label_types = {\n", " \"Bidirectional\": \"BiDi\",\n", " \"3 State\": \"3State\",\n", " \"Input\": \"Input\",\n", " \"Clock Input\": \"Input\",\n", " \"Output\": \"Output\"\n", "}\n", "def io_pin(pin, x, y, type_, orientation, label):\n", " label_type = global_label_types[type_]\n", " if orientation == \"In\":\n", " x -= 300\n", " else:\n", " x += 300\n", " pin_global_label = 'Text GLabel {:.0f} {:.0f} {:.0f} 50 {} ~ 0\\n{}\\n'.format(x, y, 0 if orientation == \"In\" else 2, label_type, pin)\n", " \n", " if label:\n", " note = \"Text HLabel {:.0f} {:.0f} {:.0f} 50 {} ~ 0\\n{}\\n\".format(x, y+150, 0 if orientation == \"In\" else 2, label_type, label)\n", " return pin_global_label+note\n", " return pin_global_label" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "main_file_template = \"\"\"EESchema Schematic File Version 4\n", "EELAYER 30 0\n", "EELAYER END\n", "$Descr User 86614 86614\n", "encoding utf-8\n", "Sheet 1 1\n", "Title \"\"\n", "Date \"\"\n", "Rev \"\"\n", "Comp \"\"\n", "Comment1 \"\"\n", "Comment2 \"\"\n", "Comment3 \"\"\n", "Comment4 \"\"\n", "$EndDescr\n", "%COMPONENTS%\n", "$EndSCHEMATC\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lines = []\n", "GUID_SEED = int(time.time())\n", "\n", "for c in DISPLAY_CELLS:\n", " x, y = to_ref_xy(c[0], c[1])\n", " ref = to_ref(c[0], c[1])\n", " if ref in IO_PINS:\n", " io = IO_PINS[ref]\n", " x = 1 if io[3] == \"In\" else 2\n", " y = int(io[0])\n", " if y >= 80:\n", " x += 50\n", " y -= 80\n", " y *= 2\n", " else:\n", " io = None\n", " x += 4\n", " y -= 18\n", " y += 2\n", " x += 2\n", " type_ = c[4][:-5] if \".flip\" in c[4] else c[4]\n", " coords = x*1200, y*350\n", " if io:\n", " lines.append(io_pin(io[0], coords[0], coords[1], io[1], io[3], io[2]))\n", "\n", " lines.append(component(\"CG24-cells:\"+type_, type_, ref, createId(), coords[0], coords[1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Write the schematics" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# !!!!!!!! THIS WILL OVERWRITE COMPLETELY YOUR WORK ON THE MAIN_SCHEMATICS!!!!!!!\n", "# IF YOU ARE NOT AFRAID, UNCOMMENT THE NEXT LINE\n", "#with open(main_schematics, \"w\") as w:\n", "# w.write(main_file_template.replace(\"%COMPONENTS%\", \"\".join(lines)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Export Pinout as Markdown" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for r in csv.DictReader(open(pinout), delimiter=\"\\t\"):\n", " print(\"| \"+ \" | \".join([r[\"Pin\"], r[\"Type\"], r[\"Name\"]])+\" |\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Export as one image\n", "\n", "Code is copy-pasted from viewer mainly... sorry 'bout that" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "subimg = tst.copy()\n", "#subimg = norm(subimg)\n", "subimg = cv2.cvtColor(subimg, cv2.COLOR_GRAY2BGR)\n", "rect_overlay = subimg.copy()\n", "off = grid_start[0]\n", "bound_y, bound_x, _ = subimg.shape\n", "# font \n", "font = cv2.FONT_HERSHEY_SIMPLEX \n", "# fontScale \n", "fontScale = 1\n", "# Blue color in BGR \n", "color = (255, 0, 0)\n", "color_error = (0, 0, 255)\n", "color_black = (0, 0, 0)\n", "color_white = (255, 255, 255)\n", "color_gray = (50,50,50) #(255, 255, 255)\n", "# Line thickness of 2 px \n", "thickness = 2\n", "for x, y, w, h, pattern, rects, score, bc_x, bc_y in DISPLAY_CELLS:\n", " c_x, c_y = (rects[0][0], rects[0][1])\n", "\n", " if (c_x < -50 or c_x > bound_x) and (c_y < -50 or c_y > bound_y):\n", " continue\n", "\n", " for r in rects:\n", " cv2.rectangle(rect_overlay, (r[0], r[1]), (r[2], r[1]+max(r[3]-r[1], 55)), COLORS[patterns_idx[pattern] % len(COLORS)], cv2.FILLED)\n", "\n", "alpha = 0.4\n", "subimg = cv2.addWeighted(rect_overlay, alpha, subimg,1-alpha, gamma=0)\n", "\n", "for pin in range(0, 30):\n", " c_x, c_y = (2050+20, +40+2300 + 287*pin)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(pin+1), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (10810, +40+2300 + 287*pin)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(90-pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (2250+20 + 288*pin, +40+ 2100)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(120-pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " c_x, c_y = (2250+20 + 288*pin, 10860)\n", " if (-50 < c_x < bound_x + 50) and (-50 < c_y < bound_y + 50):\n", " cv2.rectangle(subimg, (c_x-10, c_y-33), (c_x+70, c_y+20), color_white, cv2.FILLED)\n", " cv2.putText(subimg, str(31+pin), (c_x, c_y), font, fontScale, color_black, thickness, cv2.LINE_AA)\n", " \n", " \n", " \n", "for x, y, w, h, pattern, rects, score, bc_x, bc_y in DISPLAY_CELLS:\n", " textX = (x) + 5 \n", " textY = (y) + 5\n", "\n", " if (textX < -50 or textX > bound_x) and (textY < -50 or textY > bound_y):\n", " continue\n", "\n", " ref = to_ref(x, y)\n", "\n", " textsize = cv2.getTextSize(pattern, font, fontScale, thickness)[0]\n", " #textX = (x-offset[0]) + (w - textsize[0]) // 2\n", " #textY = (y-offset[1]) + (h + textsize[1]) // 2\n", " textY += textsize[1]\n", " #if ref in REFERENCES:\n", " # color_txt = color if pattern.replace(\".flip\", \"\") == REFERENCES[ref] else color_error\n", " #else:\n", " color_txt = color_white if ref not in REFERENCES else color\n", " cv2.putText(subimg, pattern, (textX, textY), font, fontScale, color_txt, thickness, cv2.LINE_AA)\n", " cv2.putText(subimg, \"[%s]\" % ref, (textX, textY+textsize[1]+2), font, fontScale*0.5, color_txt, 1, cv2.LINE_AA)\n", " #print(x, y, w, h, pattern)\n", "\n", "cv2.imwrite(\"DL-1927.jpg\", subimg)\n", "del subimg\n", "print(\"Finished\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.1" } }, "nbformat": 4, "nbformat_minor": 4 }