Hey buddies !! Do you love DSLR kind of blur images or portrait mode on your phone but don’t have enough money to buy one. Why not create your own blur background effect? Wondering How !!! Then just give a try to the below article and create your own filter to blur not just the background but also the foreground.

The technique to blur the image is simple, it averages out the pixels surrounding  the pixel using a kernel.

Here we will use OpenCV to perform our task efficiently.

Importing libraries

We’ll be using the following libraries of python.

  • “cv2” for video capturing, frame reading, pixel management, color management of the video,
  • “date time” for delays and
  • “os” for handlling paths
import cv2
import datetime
import os

Blurring the Background

For blurring the background, I have created a function named blur_background() that takes two arguments : the image and the grayscale i.e. black and white image.

Inside the function, I’ll find the face in the image. If faces are found, the positions of detected faces will be stored in a variable face. I have used Haar Cascade to detect the face and stored the result in face variable. x_face, y_face, w_face, h_face are 2 coordinates and width , depth of face respectively. Once we get these locations, we can create a ROI for the face and blur the background. The ROI for the face is stored in a roi_face variable.

To blur the image, I have used cv2.blur() function that takes image name and kernel size as input. The function smooths an image using the kernel which is represented as:

Syntax: cv2.blur(src, ksize[, dst[, anchor[, borderType]]])

Parameters:
src: It is the image which is to be blurred.
ksize: A tuple representing the blurring kernel size.
dst: It is the output image of the same size and type as src.
anchor: It is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.
borderType: It depicts the kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANTcv2.BORDER_REFLECT, etc
Return Value: It returns an image.

After blurring the image, I’ll replace the blurred foreground with the ROI of face stored in roi_face variable.

Background Blur
def blur_background(grayscale, img):    
    face = cascade_face.detectMultiScale(grayscale, 1.3, 5)
    
    for (x_face, y_face, w_face, h_face) in face:
        #storing face
        roi_face= img[y_face: y_face+ h_face, x_face: x_face+ w_face]
        img = cv2.blur(img,(10,10))
        img[y_face: y_face+ h_face, x_face: x_face+ w_face]=roi_face

    #return image        
    return img

Blurring the Foreground

For blurring the foreground, I have created a function named blur_foreground() that takes two arguments : the image and the grayscale i.e. black and white image.

Inside the function, I’ll find the face in the image. If faces are found, the positions of detected faces will be stored in a variable face. I have used Haar Cascade to detect the face and stored the result in face variable. x_face, y_face, w_face, h_face are 2 coordinates and width , depth of face respectively. Once we get these locations, we can create a ROI for the face and blur the background. The ROI for the face is stored in a roi_face variable.

To blur the image, I have used cv2.blur() function that takes roi_face (region that needs to be blurred) and kernel size as input and store its result in roi_face. After blurring the region, I’ll replace the unblurred foreground with the blurred ROI of face stored in roi_face variable.

def blur_foreground(grayscale, img):
    face = cascade_face.detectMultiScale(grayscale, 1.3, 5)

    for (x_face, y_face, w_face, h_face) in face:
        roi_face= img[y_face: y_face+ h_face, x_face: x_face+ w_face]
        roi_face = cv2.blur(roi_face,(10,10))
        img[y_face: y_face+ h_face, x_face: x_face+ w_face]=[0,0,0]
        img[y_face: y_face+ h_face, x_face: x_face+ w_face]=      
                cv2.add(roi_face, img[y_face: y_face+ h_face, x_face: x_face+ w_face])


    #return image        
    return img 
Foreground Blur

Main block to call these functions

Now, I will create an object to capture the video and set the path to store the file. If the file already exists, then we’ll update the path therefore, the code is placed in try catch block to handle the exceptions.

vc = cv2.VideoCapture(0) 
path= os.getcwd()
# Create directory
dirName = 'tempimage_folder'
try:
    os.mkdir(dirName)
except FileExistsError:
    print("Directory " , dirName ,  " already exists")
path= path+'/'+dirName

After creating the directory, next we to have capture the image and convert it into the grayscale image using cv2.cvtColor(). Then, I’ll ask the user to enter his choice, whether he wants to blur backgorund or foreground. Based on his choice, I’ll call the specified function by passing necessary parameters. The function will return the result.

After getting the result, I’ll display the image using cv2.imshow() function and then save the image with name appended with current date and time. After that, file will be saved using the cv2.imwrite() function which writes the next video frame and cv2.release() function will release the camera or current capturing device.

choice = input("What do you want to perform? (foreground blur/ background blur)")
cascade_face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cnt=0
while cnt<500:
    #read status of camera and frame
    _, img = vc.read() 
    #convert image ot grayscale
    grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    
    #result from function
    if choice == "foreground":
        final = blur_foreground(grayscale, img) 
    elif choice == "background":
        final = blur_background(grayscale, img) 
    else:
        print("Invalid choice !")
        break
    
    #showing captured image
    cv2.imshow('Video', final) 
    
    #name of our image, with current time, so that it has new name each time.
    string = "pic"+str(datetime.datetime.now())+".jpg"
    #save image
    cv2.imwrite(os.path.join(path, string),final)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break 
    cnt+=1
vc.release() 
cv2.destroyAllWindows() 

Implementation

Conclusion

So, we have finally implemented our own tool to blur foreground and background. Feel free to share your reviews.

Suniti Jain


79 Comments

Bitcoin Halving Era Review · July 9, 2020 at 7:46 pm

Woh I love your posts, saved to my bookmarks!

http://dermafilcream.org/ · July 9, 2020 at 8:15 pm

I read this piece of writing completely about the comparison of newest and earlier technologies, it’s awesome article.

Lyttleton · July 9, 2020 at 8:30 pm

Hello there, just became alert to your blog through Google, and found that it is truly informative.
I’m gonna watch out for brussels. I will be grateful if you continue this
in future. Lots of people will be benefited from your writing.
Cheers!

http://totalbodyketo.org/ · July 9, 2020 at 8:36 pm

I went over this web site and I think you have a lot of superb
information, saved to bookmarks (:.

Active Finesse Keto Reviews · July 9, 2020 at 8:40 pm

Would love to forever get updated outstanding web
blog!

http://activefinesseketoblend.net/ · July 9, 2020 at 8:42 pm

I couldn?t refrain from commenting. Exceptionally well written!

Eco Serve Device · July 9, 2020 at 8:43 pm

I have been examinating out a few of your articles and it’s pretty good stuff.
I will make sure to bookmark your blog.

http://beauserum.com/ · July 9, 2020 at 8:44 pm

Just want to say your article is as amazing.
The clarity on your post is simply cool and that i can assume you’re a professional in this subject.

Fine with your permission let me to seize your
RSS feed to keep updated with coming near near
post. Thanks one million and please carry on the rewarding
work.

Vital Synergy Keto · July 9, 2020 at 8:54 pm

Please let me know if you’re looking for a author for your site.
You have some really great articles and I think I would be a
good asset. If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine.
Please shoot me an e-mail if interested. Thank you!

Signal Tech Wifi Booster Reviews · July 9, 2020 at 9:01 pm

I have been reading out a few of your posts and
i must say clever stuff. I will surely bookmark your website.

http://bstdrive.com/ · July 9, 2020 at 9:03 pm

Hey very cool web site!! Man .. Beautiful .. Wonderful ..
I’ll bookmark your website and take the feeds additionally…I am glad to find a lot of helpful info here within the put up, we want
develop more techniques in this regard, thanks for sharing.

Eco Serve Power Saver · July 9, 2020 at 9:03 pm

Thank you for sharing superb informations. Your web site is
so cool. I’m impressed by the details that you have on this web site.
It reveals how nicely you understand this subject. Bookmarked
this web page, will come back for extra articles.

You, my pal, ROCK! I found simply the info I already searched everywhere and
simply couldn’t come across. What a great website.

EcoServe Energy Saver Reviews · July 9, 2020 at 9:04 pm

You have brought up a very good points, thanks for the post.

Beau Skin Serum Review · July 9, 2020 at 9:10 pm

This text is priceless. How can I find out more?

Signal Tech Wifi Booster · July 9, 2020 at 9:14 pm

Amazing! Its really amazing paragraph, I have got much clear idea concerning from
this article.

DermaFil Skin Care · July 9, 2020 at 9:15 pm

I believe this is one of the such a lot significant info for me.

And i’m happy reading your article. However want to observation on some basic issues, The site taste is wonderful, the articles is truly great :D. Good process, cheers.

Here is my page – DermaFil Skin Care

Lively Effect CBD · July 9, 2020 at 9:20 pm

Pretty nice post. I just stumbled upon your blog
and wished to say that I have truly enjoyed browsing your blog posts.

In any case I will be subscribing to your feed and I hope you write again soon!

http://laivelleskinserum.net/ · July 9, 2020 at 9:29 pm

Thanks on your marvelous posting! I really enjoyed reading it, you happen to be a great author.
I will always bookmark your blog and will come back from now
on. I want to encourage continue your great posts, have a nice day!

DermaFil Ageless Moisturizer · July 9, 2020 at 9:42 pm

This is really interesting, You are a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of your great post.
Also, I have shared your website in my social networks!

Calm Purity Skin Serum · July 9, 2020 at 9:49 pm

always i used to read smaller content that as well clear their motive,
and that is also happening with this paragraph which I am reading at this place.

Revo Keto · July 9, 2020 at 9:52 pm

I was able to find good advice from your
content.

Premier Male Enhancement Reviews · July 9, 2020 at 9:56 pm

Appreciate it for helping out, excellent information.

Novum Health Keto Reviews · July 9, 2020 at 10:06 pm

Very great information can be found on website.

Blaux Wearable AC · July 9, 2020 at 10:11 pm

I believe other website owners should take
this site as an example, very clean and great user pleasant style.

Vital Synergy Keto · July 9, 2020 at 10:14 pm

I think the admin of this web site is genuinely working hard for his
web site, as here every material is quality based data.

Active Finesse Keto Blend Review · July 9, 2020 at 10:14 pm

Hi there! This blog post could not be written any better!
Going through this post reminds me of my previous roommate!

He continually kept talking about this. I’ll forward this information to him.
Pretty sure he’s going to have a great read.
Thanks for sharing!

MegaXXL · July 9, 2020 at 10:36 pm

Saved as a favorite, I like your site!

http://biogoldcbd.net/ · July 9, 2020 at 10:56 pm

Hello there! I just wish to give you a big thumbs up for the great information you have right here on this post.
I’ll be coming back to your web site for more soon.

http://laivelleskinserum.com/ · July 9, 2020 at 11:10 pm

Keep up the good work, I read few content on this site and I believe that your web blog is
rattling interesting and holds circles of fantastic info.

http://naturalsourcecbd.net/ · July 9, 2020 at 11:20 pm

Right here is the perfect web site for anyone who wishes to find out about
this topic. You understand so much its almost tough to argue with you (not that I really would want to…HaHa).
You certainly put a brand new spin on a topic
that’s been discussed for ages. Excellent stuff, just excellent!

Shark Lean · July 9, 2020 at 11:23 pm

Hello. fantastic job. I did not expect this. This is a splendid story.
Thanks!

Keto Lyte Dietary Supplement · July 9, 2020 at 11:25 pm

Nice read, I just passed this onto a friend who was doing some research on that.
And he actually bought me lunch as I found it for him smile
Thus let me rephrase that: Thanks for lunch!

KetoFab Reviews · July 9, 2020 at 11:28 pm

I cherished up to you will receive carried out proper here.
The cartoon is attractive, your authored subject
matter stylish. nevertheless, you command get bought an impatience over that
you wish be delivering the following. in poor health no doubt come more
formerly again as exactly the same just about a lot frequently inside of case you shield this
increase.

http://rapidboostketo.org/ · July 9, 2020 at 11:29 pm

For most up-to-date information you have to visit internet
and on web I found this web page as a best site for newest updates.

http://totalbodyketo.org/ · July 9, 2020 at 11:36 pm

This site is my aspiration, really good style and Perfect written content.

http://himsmaleenhancement.net/ · July 9, 2020 at 11:40 pm

Thank you so much for giving everyone a very marvellous chance to read critical reviews from this web site.
It can be very brilliant and also full of a lot of fun for
me and my office mates to search your web site at minimum thrice in one week
to read the latest items you have got. And lastly, I’m also usually satisfied with the perfect concepts you serve.
Some 2 tips in this posting are in reality the best I’ve had.

http://laivelleskin.com/ · July 9, 2020 at 11:41 pm

Having read this I thought it was extremely informative.
I appreciate you spending some time and effort to put this informative article together.

I once again find myself personally spending way too much time both reading and leaving comments.
But so what, it was still worth it!

http://nulavance.org/ · July 9, 2020 at 11:48 pm

Everything is very open with a very clear clarification of the issues.

It was truly informative. Your site is useful.

Thank you for sharing!

UV Cooler Reviews · July 9, 2020 at 11:48 pm

I visited various web sites however the audio feature for audio songs
present at this website is really excellent.

Macro Keto Pills · July 9, 2020 at 11:55 pm

I do not even know the way I finished up right here, but
I assumed this submit was good. I don’t realize who you might be however definitely you’re going to a well-known blogger in case you are not already 😉 Cheers!

http://bstdrive.com/ · July 9, 2020 at 11:55 pm

Good way of explaining, and good paragraph to take facts regarding
my presentation focus, which i am going to present
in school.

Active Finesse Keto Blend Reviews · July 10, 2020 at 12:05 am

Regards for all your efforts that you have put in this.
Very interesting info.

iHeadphones Reviews · July 10, 2020 at 12:26 am

Wow, that’s what I was seeking for, what a data! existing here at this webpage,
thanks admin of this web page.

Mystic Style Skin Cream · July 10, 2020 at 12:28 am

I’ve been surfing online more than 3 hours today, yet I never found any interesting article like yours.
It’s pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as
you did, the web will be a lot more useful than ever before.

Eco Serve Reviews · July 10, 2020 at 12:32 am

This website truly has all the info I wanted about this subject and didn?t know
who to ask.

Delilah · July 10, 2020 at 12:33 am

We wish to thank you all over again for the lovely ideas you offered Janet when preparing
her post-graduate research and, most importantly, with regard to providing many of the ideas within a blog post.

Provided we had been aware of your web page a year ago,
we might have been rescued from the pointless measures we were participating in. Thanks to you.

Bernad · July 10, 2020 at 12:34 am

Now I am ready to do my breakfast, once having my breakfast coming over again to read more news.

http://blauxairconditioner.org/ · July 10, 2020 at 12:34 am

Some really great blog posts on this web site, appreciate
it for contribution.

Lily · July 10, 2020 at 12:41 am

I dugg some of you post as I cerebrated they were extremely helpful handy.

Lynda · July 10, 2020 at 12:45 am

If you are going for finest contents like myself, simply pay a
quick visit this web page everyday for the reason that it offers
feature contents, thanks

Revo Keto Review · July 10, 2020 at 12:50 am

Simply a smiling visitor here to share the love
(:, btw outstanding pattern.

Power Instinct Male Enhancement Review · July 10, 2020 at 12:51 am

Thanks for some other informative site. The place else may just I am getting that type of info written in such a perfect approach?
I have a challenge that I am simply now operating on, and I have been at
the look out for such info.

James · July 10, 2020 at 12:55 am

Amazing issues here. I’m very happy to look your post. Thanks a lot and
I am taking a look ahead to contact you. Will you kindly drop me a e-mail?

Maurine · July 10, 2020 at 1:09 am

Spot on with this write-up, I truly believe that this web site needs a lot more attention. I’ll
probably be back again to read through more, thanks for the advice!

Genny · July 10, 2020 at 1:10 am

Hello to all, the contents existing at this website are truly amazing for
people experience, well, keep up the good work fellows.

Sherl · July 10, 2020 at 1:13 am

Wonderful blog! I found it while searching on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!

Thanks

Shark Lean · July 10, 2020 at 1:15 am

Wow, amazing weblog structure! How long have you been blogging
for? you made blogging look easy. The entire look
of your site is magnificent, as well as the content!

Bitcoin Halving Era Reviews · July 10, 2020 at 1:30 am

Some truly interesting information, well written and loosely user friendly.

Villiam · July 10, 2020 at 1:30 am

I think this is among the so much vital information for me.
And i am satisfied reading your article. However should commentary on some common issues, The website
taste is great, the articles is really great
: D. Excellent activity, cheers

Ascension Keto · July 10, 2020 at 1:42 am

Yay google is my world beater aided me to find this great site!

electronics-pluz · July 10, 2020 at 1:57 am

Everyone loves what you guys are usually up too. This kind
of clever work and reporting! Keep up the amazing
works guys I’ve incorporated you guys to my own blogroll.

DermaFil Anti Aging Cream · July 10, 2020 at 2:01 am

I got what you intend,bookmarked, very decent internet
site.

SignalTech · July 10, 2020 at 2:02 am

Wow! This could be one particular of the most beneficial blogs We’ve ever arrive
across on this subject. Actually Excellent.
I’m also an expert in this topic so I can understand your effort.

TruFlexen · July 10, 2020 at 2:10 am

Hello there, You’ve done an incredible job. I will definitely digg it and personally recommend to my friends.
I am confident they will be benefited from this website.

Jessy · July 10, 2020 at 2:20 am

Excellent article! We will be linking to this particularly great content on our site.

Keep up the great writing.

UV Cooler · July 10, 2020 at 2:42 am

I visit everyday a few web pages and information sites to read articles, except
this weblog presents feature based writing.

Bloom Field CBD Reviews · July 10, 2020 at 3:16 am

Its such as you read my mind! You seem to grasp so much approximately this, like you wrote the ebook in it or something.
I feel that you just could do with some p.c. to drive the message home
a bit, however other than that, this is wonderful blog.

A great read. I’ll definitely be back.

Keto Fab · July 10, 2020 at 3:16 am

I loved as much as you will receive carried out right here.
The sketch is attractive, your authored material stylish.
nonetheless, you command get got an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this hike.

shine · July 10, 2020 at 3:24 am

Awesome work once again! I am looking forward for your next post=)

Ambika · July 10, 2020 at 3:57 am

Good post and right to the point. I don’t know if this
is actually the best place to ask but do you folks have any thoughts on where
to employ some professional writers? Thanks in advance 🙂

Kumar jha · July 10, 2020 at 5:29 am

Greetings! Very useful advice within this article! It’s the
little changes that make the largest changes. Thanks a lot for sharing!

Novum Keto Pills · July 10, 2020 at 10:06 am

If some one wants expert view about blogging afterward i suggest him/her to go to
see this blog, Keep up the pleasant work.

    Data-stats · July 10, 2020 at 5:53 pm

    Thank You!

BioGold CBD · July 10, 2020 at 10:44 am

Thanks for the marvelous posting! I actually enjoyed reading it,
you’re a great author.I will be sure to bookmark your blog and definitely will come back from
now on. I want to encourage continue your great job, have a nice morning!

Chrinstine · July 11, 2020 at 12:52 am

I’ve been browsing online more than 3 hours today,
yet I never found any interesting article like yours. It’s pretty worth enough for me.
Personally, if all webmasters and bloggers made good content as you did,
the web will be much more useful than ever before.

Amy · July 11, 2020 at 7:41 am

Greetings! I’ve been following your weblog for a while now and finally got the courage to go ahead and give
you a shout out from Humble Texas! Just wanted to say keep up the good
job! Hola! I’ve been reading your website for some time now and finally got the
bravery to go ahead and give you a shout out from Kingwood Texas!
Just wanted to mention keep up the good job! Ahaa,
its fastidious discussion on the topic of this piece of writing
at this place at this web site, I have read all that, so at this
time me also commenting at this place.

http://iacc-scu.org/fat-burning-diets-the-fact-9/ · July 11, 2020 at 10:44 am

Superb, what a weblog it is! This weblog presents valuable data to
us, keep it up.

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert