I'm trying to subtract the background of image and then draw contours.
I'm using the removebg API to subtract the background, and I want to take the image result and draw contours on it.
Removing the background:
rmbg = RemoveBg("MY_KEY_API", "error.log")
img_no_bg = rmbg.remove_background_from_img_file("images/imagetest.png")
I want to convert the result imagetest_no-bg.png to grayscale, but I can't use img_no_bg as the attribute for the function imread().
image = cv2.imread(img_no_bg)
gray = gray = cv2.cvtColor(img_no_bg,cv2.COLOR_BGR2GRAY)
Related
I have a script that loads an image and using selectROI() allows me to select and crop a specific part of that image and get the contours of just that part alone. But how can I search if are there any other contours in the original image just like the one I selected and cropped? My goal is to teach a shape and verify if that shape occurs in any other parts of that image or any other image that I load after, hopefully even being able to have a certain tolerance of correspondence.
I could try something like object detection using HAAR Cascade or YOLO, but I am positive that there is a way to do it without relying on heavy-weight computation AI models, especially because I want to use it on static images, not on video. I say that because that is how it is made on industrial vision systems. You only need to load a single image and select the object that you want to detect so the contours can be drawn. We you load another image, the software will look for these contours up to a certain level of correspondence.
import cv2 as cv
import numpy as np
# Load Image
img = cv.imread('C:/Users/ALEMAC/Downloads/geometricShapes.jpg')
#Selecting ROI
imgdraw = cv.selectROI(img)
cropimg = img[int(imgdraw[1]):int(imgdraw[1]+imgdraw[3]), int(imgdraw[0]):int(imgdraw[0]+imgdraw[2])] #displaying the cropped image as the output on the screen
cv.imshow('Cropped_image',cropimg)
blank = np.zeros(cropimg.shape[:2], dtype='uint8') # creates a blank img, with the same size as our geometricShapes img
gray = cv.cvtColor(cropimg, cv.COLOR_BGR2GRAY)
blur = cv.GaussianBlur(gray,(3,3), cv.BORDER_DEFAULT)
# Find edges using contours method
ret, thresh = cv.threshold(blur, 125,255, cv.THRESH_BINARY)
#cv.imshow('Thresh', thresh)
contours, hierachies = cv.findContours(thresh, cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(blank,contours,-1,(255,255,255),thickness=1)
cv.imshow('Contours', blank)
cv.waitKey(0)
I have been trying to write a code to extract cracks from an image using thresholding. However, I wanted to keep the background black. What would be a good solution to keep the outer boundary visible and the background black. Attached below is the original image along with the threshold image and the code used to extract this image.
import cv2
#Read Image
img = cv2.imread('Original.png')
# Convert into gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Image processing ( smoothing )
# Averaging
blur = cv2.blur(gray,(3,3))
ret,th1 = cv2.threshold(blur,145,255,cv2.THRESH_BINARY)
inverted = np.invert(th1)
plt.figure(figsize = (20,20))
plt.subplot(121),plt.imshow(img)
plt.title('Original'),plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(inverted,cmap='gray')
plt.title('Threshold'),plt.xticks([]), plt.yticks([])
Method 1
Assuming the circle in your images stays in one spot throughout your image set you can manually create a black 'mask' image with a white hole in the middle, then overlay it on the final inverted image.
You can easily make the mask image using your favorite image editor's magic wand tool.
I made this1 by also expanding the circle inwards by one pixel to take into account some of the pixels the magic wand tool couldn't catch.
You would then use the mask image like this:
mask = cv2.imread('/path/to/mask.png')
masked = cv2.bitwise_and(inverted, inverted, mask=mask)
Method 2
If the circle does NOT stay is the same spot throughout your entire image set you can try to make the mask from all the fully black pixels in your original image. This assumes that the 'sample' itself (the thing with the cracks) does not contain fully black pixels. Although this will result in the text on the bottom left to be left white.
# make all the non black pixels white
_,mask = cv2.threshold(gray,1,255,cv2.THRESH_BINARY)
1 The original is not the same size as your inverted image and thus the mask I made won't actually fit, you're gonna have to make it yourself.
I would like to achieve something similar to this:
I currently have the image on the red background but I am unsure how to draw a translucent rectangle such as on the image above to put the text on in order to make it pop out more. I’m pretty sure it can be achieved using OpenCV but I am fairly new to Python and it seems very confusing. (I can’t seem to do it properly and it’s starting to annoy me). Here is my current image (ignore the white outline):
Here is one way to achieve the same results in Python/OpenCV.
Read the input
Crop the desired region to darken
Create the same sized black image
Blend the two image (crop 75% and black 25%)
Draw text on the blended image
Copy the text image back to the same location in the input
Save results
Input:
import cv2
import numpy as np
# load image
img = cv2.imread("chimichanga.jpg")
# define undercolor region in the input image
x,y,w,h = 66,688,998,382
# define text coordinates in the input image
xx,yy = 250,800
# compute text coordinates in undercolor region
xu = xx - x
yu = yy - y
# crop undercolor region of input
sub = img[y:y+h, x:x+w]
# create black image same size
black = np.zeros_like(sub)
# blend the two
blend = cv2.addWeighted(sub, 0.75, black, 0.25, 0)
# draw text on blended image
text = cv2.putText(blend, "CHIMICHANGA", (xu,yu), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), cv2.LINE_8, bottomLeftOrigin=False )
# copy text filled region onto input
result = img.copy()
result[y:y+h, x:x+w] = text
# write result to disk
cv2.imwrite("chimichanga_result.jpg", result)
# display results
cv2.imshow("BLEND", blend)
cv2.imshow("TEXT", text)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:
I'm cropping an image like this:
self.rst = self.img_color[self.param_a_y:self.param_b_y,
self.param_a_x:self.param_b_x:, ]
How do I copy this image back to the original one. The data I have available are the coordinates of the original image, which makes the center of the crop.
Seems like there's nocopy_to() function for python
I failed myself getting copy_to() working a few days ago, but came up with a difeerent solution: You can uses masks for this task.
I have an example at hand which shows how to create a mask from a defined colour range using inrange. With that mask, you create two partial images (=masks), one for the old content and one for the new content, the not used area in both images is back. Finally, a simple bitwise_or combines both images.
This works for arbitrary shapes, so you can easily adapt this to rectangular ROIs.
import cv2
import numpy as np
img = cv2.imread('image.png')
rows,cols,bands = img.shape
print rows,cols,bands
# Create image with new colour for replacement
new_colour_image= np.zeros((rows,cols,3), np.uint8)
new_colour_image[:,:]= (255,0,0)
# Define range of color to be exchanged (in this case only one single color, but could be range of colours)
lower_limit = np.array([0,0,0])
upper_limit = np.array([0,0,0])
# Generate mask for the pixels to be exchanged
new_colour_mask = cv2.inRange(img, lower_limit, upper_limit)
# Generate mask for the pixels to be kept
old_image_mask=cv2.bitwise_not(new_colour_mask)
# Part of the image which is kept
img2= cv2.bitwise_and(img,img, old_image_mask)
# Part of the image which is replaced
new_colour_image=cv2.bitwise_and(new_colour_image,new_colour_image, new_colour_mask)
#Combination of the two parts
result=cv2.bitwise_or(img2, new_colour_image)
cv2.imshow('image',img)
cv2.imshow('mask',new_colour_mask)
cv2.imshow('r',result)
cv2.waitKey(0)
How do you draw semi-transparent polygons using the Python Imaging Library?
Can you draw the polygon on a separate RGBA image then use the Image.paste(image, box, mask) method?
Edit: This works.
from PIL import Image
from PIL import ImageDraw
back = Image.new('RGBA', (512,512), (255,0,0,0))
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.polygon([(128,128),(384,384),(128,384),(384,128)],
fill=(255,255,255,127),outline=(255,255,255,255))
back.paste(poly,mask=poly)
back.show()
http://effbot.org/imagingbook/image.htm#image-paste-method
I think #Nick T's answer is good, but you need to be careful when using his code as written with a very large background image, especially in the case that you may be annotating several polygons on said image. This is something I do when processing huge satellite images with some object detection code and annotating the detections using a transparent rectangle. To make the code efficient no matter the size of the background image, I make the following suggestion.
I would modify the solution to specify that the polygon image that you will paste be only as large as required to hold the polygon, not the same size as the back image. The coordinates of the polygon are specified with respect to the local bounding box, not the global image coordinates. Then you paste the polygon image at the offset in the larger background image.
import Image
import ImageDraw
img_size = (512,512)
poly_size = (256,256)
poly_offset = (128,128) #location in larger image
back = Image.new('RGBA', img_size, (255,0,0,0) )
poly = Image.new('RGBA', poly_size )
pdraw = ImageDraw.Draw(poly)
pdraw.polygon([ (0,0), (256,256), (0,256), (256,0)],
fill=(255,255,255,127), outline=(255,255,255,255))
back.paste(poly, poly_offset, mask=poly)
back.show()
Using the Image.paste(image, box, mask) method will convert the alpha channel in the pasted area of the background image into the corresponding transparency value of the polygon image.
The Image.alpha_composite(im1,im2) method utilizes the alpha channel of the "pasted" image, and will not turn the background transparent. However, this method again needs two equally sized images.