How to remove small particle background noise from an image?

2024/11/13 8:00:50

I'm trying to remove gradient background noise from the images I have. I've tried many ways with cv2 without success.

sample

Converting the image to grayscale at first to make it lose some gradients that may help to find the contours.

Imgur

Does anybody know of a way to deal with this kind of background? I even tried taking a sample from the corners and applying some kind of kernel filter.

Answer

One way to remove gradients is to use cv2.medianBlur() to smooth out the image by taking the median of all pixels under a kernel. Then to extract the letters, you can perform cv2.adaptiveThreshold().

The blur removes most of the gradient noise. You can change the kernel size to remove more but it will also remove the details of the letters

enter image description here

Adaptive threshold the image to extract characters. From your original image, it seems like gradient noise was added onto the the letters c, x, and z to make it blend into the background.

enter image description here

Next we can perform cv2.Canny() to detect edges and obtain this

enter image description here

Then we can do morphological opening using cv2.morphologyEx() to clean up the small noise and enhance details

enter image description here

Now we dilate using cv2.dilate() to obtain a single contour

enter image description here

From here, we find contours using cv2.findContours(). We iterate through each contour and filter using cv2.contourArea() with a minimum and maximum area to obtain bounding boxes. Depending on your image, you may have to adjust the min/max area filter. Here's the result

enter image description here

import cv2
import numpy as npimage = cv2.imread('1.png')blur = cv2.medianBlur(image, 7)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,3)canny = cv2.Canny(thresh, 120, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)
dilate = cv2.dilate(opening, kernel, iterations=2)cnts = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]min_area = 500
max_area = 7000
for c in cnts:area = cv2.contourArea(c)if area > min_area and area < max_area:x,y,w,h = cv2.boundingRect(c)cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)cv2.imshow('blur', blur)
cv2.imshow('thresh', thresh)
cv2.imshow('canny', canny)
cv2.imshow('opening', opening)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.waitKey(0)
https://en.xdnf.cn/q/72196.html

Related Q&A

Running commands from within python that need root access

I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs …

How not to plot missing periods

Im trying to plot a time series data, where for certain periods there is no data. Data is loaded into dataframe and Im plotting it using df.plot(). The problem is that the missing periods get connected…

Disabling std. and file I/O in Python sandbox implementation

Im trying to set up a Python sandbox and want to forbid access to standard and file I/O. I am running the sandbox inside of a running Python server.Ive already looked at modules like RestrictedPython a…

Extract edge and communities from list of nodes

I have dataset which has more than 50k nodes and I am trying to extract possible edges and communities from them. I did try using some graph tools like gephi, cytoscape, socnet, nodexl and so on to v…

Why is this usage of python F-string interpolation wrapping with quotes?

Code in question:a = test# 1) print(f{a}) # test# 2) print(f{ {a} }) # {test}# 3) print(f{{ {a} }}) # {test}My question is, why does case two print those quotes?I didnt find anything explicitly in the…

Adding a matplotlib colorbar from a PatchCollection

Im converting a Shapely MultiPolygon to a PatchCollection, and first colouring each Polygon like so:# ldn_mp is a MultiPolygon cm = plt.get_cmap(RdBu) num_colours = len(ldn_mp)fig = plt.figure() ax = f…

Mac 10.6 Universal Binary scipy: cephes/specfun _aswfa_ symbol not found

I cant get scipy to function in 32 bit mode when compiled as a i386/x86_64 universal binary, and executed on my 64 bit 10.6.2 MacPro1,1.My python setupWith the help of this answer, I built a 32/64 bit …

python: numpy list to array and vstack

from scipy.io.wavfile import read filepath = glob.glob(*.wav) rates = [] datas = [] for fp in filepath:rate, data = read(fp)rates.append(rate)datas.append(data)I get a list datas which is :[array([0, 0…

Django Unittests Client Login: fails in test suite, but not in Shell

Im running a basic test of my home view. While logging the client in from the shell works, the same line of code fails to log the client in when using the test suite.What is the correct way to log the …

Icon overlay issue with Python

I found some examples and topics on this forum about the way to implement an icon overlay handler with Python 2.7 & the win32com package but it does not work for me and I dont understand why. I cre…