Where exactly is the card in this photo? Image segmentation model inside a maxed-out lambda container An AWS developer built an image processing pipeline that uses a segmentation model inside a Lambda container to straighten, crop, and remove backgrounds from photos of AWS Builder Cards. The model, BiRefNet-General-Lite, runs on CPU via the rembg library, avoiding GPU costs, and the pipeline also uses a Bedrock vision model to read text from the processed image. The developer faced memory constraints, as the initial model barely fit in a 10 GB Lambda container. A crooked phone photo goes in, a clean straight card image comes out - no GPU, and nothing running when nobody uploads. It runs on the biggest lambda AWS sells, and the biggest is not the same as enough. This is the 3rd article in the series about the image processing pipeline. In two previous articles we went over the whole image processing pipeline, which process AWS Builder Cards images: From anonymous photo to a published page: An event-driven, AI, image processing pipeline on AWS https://dev.to/aws-builders/from-anonymous-photo-to-a-published-page-an-event-driven-ai-image-processing-pipeline-on-aws-2m2n and also over image classification model running in lambda container, which filters out the uploaded images and filter only valid AWS Builder Card images: Is this even a valid card? Zero-shot image classification model in a lambda container https://dev.to/aws-builders/is-this-even-a-valid-card-zero-shot-image-classification-model-in-a-lambda-container-58oj Today's article is about vision segmentation model, which also runs in a lambda container, but it's role is to process the filtered image - remove background, straighten it and crop it. Specifically about this part: Somebody photographs an AWS Builder Card lying on their desk and uploads it to my collection. What arrives is not a card - it is a "photo" of a card. Tilted and with some background around it. One lambda has already looked at it before - a small, container based lambda card-detect , which filtered it as valid AWS Builder Card. See this article https://dev.to/aws-builders/is-this-even-a-valid-card-zero-shot-image-classification-model-in-a-lambda-container-58oj for more info. Now we have to clean that picture straighten, crop, remove background , which is a job of lambda function image-processor . That lambda answers the question: Where exactly is the card in this photo? The coworking between the two lambdas is simple: after the image is put into S3 images/raw/ and filtered by card-detect as a valid one, image-processor overtakes and start to processing the image. To process the image as describe above, I need an image segmentation model . The one that goes pixel by pixel and says: "card, background, card, background..." I need it to run on CPU , inside a lambda container from the same reasons as card-detect inside AWS, cheap, serverless . To find a right model to do the job I need to know the answers to the same questions, as with card-detect lambda running CLIP ViT-B-32, laion2b s34b b79k : In this case, this is the easiest one to answer. It runs on onnxruntime behind a small library called rembg , which means no PyTorch and no training framework anywhere in the image. The other two get a section each further down, and question 1 is where the story is: the model I picked first barely fit at 10 GB . Lambda also ties vCPU to memory, so that number decides how fast this thing runs, not just whether it survives. So this is an article about memory, about the bill, and about the geometry that happens after the model has stopped talking. One thing before we start, so it does not ambush you later: there are two models in this lambda. BiRefNet finds the card. Right at the end, a Bedrock vision model reads the text off the finished image. But let's start from the beginning python from rembg import new session SESSION = new session "birefnet-general-lite" As an image segmentation model, I decided to go with BiRefNet-General-Lite , loaded through rembg . The Lite is also the answer to the memory question. Remember it works on my machine meme from previous article https://dev.to/aws-builders/is-this-even-a-valid-card-zero-shot-image-classification-model-in-a-lambda-container-58oj ? Here is where I really earned it. What I was working with locally was the BiRefNet-General model. It worked fine on my machine 🤣 , so I shipped it. What I never did was to watch how much memory it was eating while it worked. I started the container at 4 GB memory. The first couple of invocations showed me the problem: Runtime.OutOfMemory, Max Memory Used: 4095 MB of 4096 . So I went to maximum I could - 10 GB memory. It worked fine, but not as per CloudWatch : Max Memory Used: 9930 MB . That's wonderful 97% of maximum container's capacity. So yet it works, but then I tested 125 MB image and it crashed. There is no 12 GB to escape to, no bigger instance type, no flag to ask for more. With standard <20 MB image 97% of the memory is out of the question. Because I could not buy more memory, I had to need less of it. The answer was lighter model from the same family: BiRefNet-General-Lite | Setup | What happened | |---|---| 4 GB + BiRefNet-General | Dies at OOM - 4095/4096 MB used | 10 GB + BiRefNet-General | works, but peaks at 9930/10240 MB | 10 GB + BiRefNet-General-Lite | median peak 7540 MB , and results are not different from non-Lite model | There was a second fix too to lower the memory consumption and that's image resize . Every upload whose longer side is over 2048px gets downscaled to maximum 2048px cap. It shrinks the whole process: smaller composite, smaller sample, smaller arrays, smaller encode. That bought me about 300-400 MB of memory, depending on a picture size. Maxing the memory does buy me one thing for free. Lambda ties vCPU to memory, so 10 GB also gets me the most vCPUs Lambda could offer 6vCPUs and this model needs every one, because there is no GPU under a lambda container. The come from the docker build There are two ways to get model weights into a container" COPY the files in, as I did with card-detect lambda see In this case, I went for option 2 and I used rembg to do it. FROM public.ecr.aws/lambda/python:3.14 ... package and requirements installation omitted ... ENV U2NET HOME=/opt/models \ NUMBA CACHE DIR=/tmp \ MPLCONFIGDIR=/tmp RUN python -c "from rembg import new session; new session 'birefnet-general-lite' " \ && chmod -R a+rX /opt/models COPY app.py ${LAMBDA TASK ROOT}/ CMD "app.handler" new session normally loads a model at runtime, but if the model is not already cached, rembg downloads it first. As being called during Docker buildz the BiRefNet weights are downloaded into /opt/models and become part of the resulting image. When Lambda starts, the weights are already there and no model download is needed at the runtime. At my volume of the cars this lambda stays still within the free tier . Above the free tier, it'd cost roughly $0.006 per card , but I would never reach it. A comparable GPU setup would cost hundreds of dollars per month even when nobody is uploading cards and that's exactly what this project is about - mostly idle. Roughly speaking, the lambda approach would start to lose its cost advantage somewhere around tens of thousands of cards per month , but in this case the lambda is clear winner. The whole lambda is actually five steps: PNG . Not every step here is done by the image segmentation model . This lambda combines AI part - BiRefNet-General-Lite model to distinguish card vs background pixels , everything else is deterministic geometry using OpenCV and numpy . I will run the whole process on this card: First, OpenCV decodes supported file image .jpg , .png , .webp , .tiff , and .bmp into an OpenCV image , while Apple's HEIC format is decoded using Pillow with HEIC support. Then the file size check for the memory reasons above happens. If the longest side is over 2048px , lambda downcales it to max cap 2048px , while smaller images are untouched. This resized image goes into the BiRefNet-general-lite segmentation model to generate the mask see next step and the same resized image is what OpenCV warps later. python MAX DIM = 2048 def process image raw bytes : img = decode bgr raw bytes ... error guard and size capture omitted ... img = downscale img, MAX DIM ... size logging omitted ... ok, buf = cv2.imencode ".png", img ... encode guard trimmed ... work bytes = buf.tobytes ... segmentation and geometry processing omitted ... The model has to decide what is the card and what is the background - so the expected output should be something, where every pixel is scored for being part of the card or part of the background. That something is called the mask, which is nothing more than black and white alpha channel stencil. That mask is produced by BiRefNet-General-Lite model, where each pixel receives a value on how strong it belongs to the backgrund. rembg then returns the result as a mask. The pixel score goes between 0 as most noncard pixel, to 255 as most card pixel. I set up the line on 127: get mask then cleans up the result with morphological operations, filling small holes and removing small specks. The result is a clean black and white stencil of the card. From this point on, the upcoming geometry operations see next steps works with that stencil, rather than the original photo. python def get mask raw bytes, session : ... docstring trimmed ... BiRefNet segmentation cutout = Image.open io.BytesIO remove raw bytes, session=session .convert "RGBA" Extract and threshold the foreground mask alpha = np.array cutout :, :, 3 , mask = cv2.threshold alpha, 127, 255, cv2.THRESH BINARY Remove holes and noise k = cv2.getStructuringElement cv2.MORPH ELLIPSE, 15, 15 mask = cv2.morphologyEx mask, cv2.MORPH CLOSE, k mask = cv2.morphologyEx mask, cv2.MORPH OPEN, k Keep only the largest connected component n, labels, stats, = cv2.connectedComponentsWithStats mask, 8 if n 1: largest = 1 + int np.argmax stats 1:, cv2.CC STAT AREA mask = np.where labels == largest, 255, 0 .astype np.uint8 return mask The returned mask for Golden Jacket card looks like this: And this is where the segmentation model's job ends . It has separated the card from the background and everything that follows is a deterministic math. When I was thinking about straightening the card, I also thought about the eye-to-brain path . Taking a photo of a card from an angle, turns its rectangular shape into a quadrilateral, as you can see in the mask above. How do I perform a perspective rectification and turn it back into a rectangle? The answer is in the corners. Lambda needs to identify the card's four corners first. A standard approach would be use OpenCV function approxPolyDP , which simplifies the detected outline into four corner points. But here's where Builder Cards fight back: their corners are rounded , so the contour does not have four sharp corners. For this reason approxPolyDP sometimes mistakenly placed a corner somewhere inside the rounded section, like here: So instead calling a approxPolyDP , the more logical step would be if lambda fits a straight line along each of the four sides of the card. Now the mask comes handy, because it tells exactly where the card's contour is. Before fitting the lines, it temporarily rotate the contour points so the card is approximately upright. This lets it separate the contour points into top, bottom, left and right edges. Because the rounded corners would distort the straight line, lambda excludes the outer 18% at each end, when selecting the contour points used for each edge. In other words, it uses the middle part of each side, where the contour follows the card's straight edge. It then fits a straight line to each of those four sections. Where two neighbouring lines intersect gives us a corner. Because the lines represent the card's straight edges rather than its rounded physical corners, those intersections can lie slightly outside the visible card. Those four intersections become the card's four corner points. Lambda then transforms those coordinates back to the original image coordinate system. The card itself is not straightened yet. These points are passed to the next step, where they are used for the actual perspective rectification. python def find quad mask : ... docstring and contour extraction omitted ... Rotate the contour so the card becomes approximately axis-aligned. cx, cy , rw, rh , ang = cv2.minAreaRect c M = cv2.getRotationMatrix2D cx, cy , ang, 1.0 P = rotate pts pts, M Compute the bounding box of the rotated contour. minx, maxx = P :, 0 .min , P :, 0 .max miny, maxy = P :, 1 .min , P :, 1 .max W, H = maxx - minx, maxy - miny bx, by = 0.18 W, 0.18 H Ignore the rounded corners when selecting edge points. cxlo, cxhi = minx + bx, maxx - bx cylo, cyhi = miny + by, maxy - by Split contour points into the four card edges. top = P P :, 1 < miny + by & P :, 0 cxlo & P :, 0 < cxhi bottom = P P :, 1 maxy - by & P :, 0 cxlo & P :, 0 < cxhi ... left and right the same way ... Fit a line to each edge and find their intersections. if min len top , len bottom , len left , len right = 15: lt, lb = fit line top , fit line bottom ll, lr = fit line left , fit line right tl, tr = intersect lt, ll , intersect lt, lr br, bl = intersect lb, lr , intersect lb, ll ... rotate corners back and fallback methods omitted ... But wait, should I blindly trust four invisible points? Well, No. For debugging reasons, encode corners draws the detected quadrilateral and its four corner points onto the original image., which is saved as images/raw/