Python opencv outline black pixels in a blank white canvas

To elaborate more of what my expected outcome is, I have attached a test.png file, and what I want this script to do.

Essentially you would somehow have to find all the black pixels and some how find the start and stop location of them.

Then I want to enlarge that, so to speak, I want to extract the selected pixels (the contents in the green square) into it’s own image and save it.

All my images are either Black and White, no other color.

Original Image

enter image description here

Outcome Image

enter image description here

Extracted from Outcome Image

enter image description here

If anyone could help me out with this, it’d be super appreciated! I’ve tried using Opencv Python to somehow find black pixels but all my attempts have failed.


Here is one way to do that in Python/OpenCV.

  • Read the input
  • Convert to gray
  • Invert polarity (regions for contours need to be white)
  • Threshold
  • Get contours
  • Get bounding boxes
  • Crop regions in input according to bounding boxes
  • Save to disk


enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread("black_pixels.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# invert polarity
gray = 255 - gray

# do adaptive threshold on gray image
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]

# Get contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
i = 1
for c in cnts:
    # create white image
    result = np.full_like(img, (255,255,255))
    # get bounding box
    x,y,w,h = cv2.boundingRect(c)
    # crop region of img using bounding box
    region = img[y:y+h, x:x+w]
    # save region to new image
    cv2.imwrite("black_region_{0}.png".format(i), region)
    i = i + 1

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("GRAY", gray)
cv2.imshow("THRESHOLD", thresh)


enter image description here