0

I'm using the code below to blur the background.

change_bg = alter_bg(model_type="pb")
change_bg.load_pascalvoc_model("xception_pascalvoc.pb")
change_bg.blur_bg(filename, low=True, output_image_name=output, detect="car")

It works, but I need to keep only the car close and in front of the photo. If there's cars far in the background, I want it blurred as well. But I'm not finding any way to do that.

fcberg
  • 764
  • 13
  • 29

1 Answers1

0

Most likely this is not the best solution, but I was able to blur all the background and keep only the main car in the center of the image by drawing a rectangle over the small cars in the background. By doing that, the algorithm is not able to recognize those cars. Then, when loading the photo again to blur the background, I load the original photo.

So, first of all, I use the instance_segmentation to find all cars like this:

segment_image = instance_segmentation()
segment_image.load_model("mask_rcnn_coco.h5", confidence=0.5)
target_classes = segment_image.select_target_classes(car=True)


results, op = segment_image.segmentImage(filename, segment_target_classes=target_classes, show_bboxes=True, extract_segmented_objects=True, output_image_name="image_new.jpg")

other_cars = []
for i in range(0, len(results["rois"])):
    roi = results["rois"][i]
    w = roi[3] - roi[1]
    h = roi[2] - roi[0]
    if max(h, w) < 350:
        other_cars.append(roi)

Then, I hide the small cars in the image I'll use on the next step.

image = cv2.imread(filename)

for roi in other_cars:
    y1 = roi[0]
    x1 = roi[1]
    y2 = roi[2]
    x2 = roi[3]
    cv2.rectangle(image, (x1, y1), (x2, y2), (46, 221, 31), cv2.FILLED)

Then I use the alter_bg:

change_bg = alter_bg(model_type="pb")
change_bg.load_pascalvoc_model("xception_pascalvoc.pb")
target_class = change_bg.target_obj("car")

But I rewrite the part where it blurs the background to load the original image.

ori_img = cv2.imread(filename)
blur_img = cv2.blur(ori_img, (16, 16), 0)
out = np.where(seg_image[1], ori_img, blur_img)
cv2.imwrite(output, out)

Done. It works for my case.

fcberg
  • 764
  • 13
  • 29