I am using OpenCV and Python.
I want to remove the upper corner part of the image.
For example I have a image originally like this:
Afterwards, I want to remove the upper triangle part.
Is there any method besides from "hard coding"?
I am using OpenCV and Python.
I want to remove the upper corner part of the image.
For example I have a image originally like this:
Afterwards, I want to remove the upper triangle part.
Is there any method besides from "hard coding"?
Pedantically speaking, you cannot remove any part of an image except a stripe on either side, reducing it's width or height. For what looks like "removal of the corner part" you can draw a background-colored triangle over that corner part. Here, assuming your desired background color is white:
import cv2
import numpy
img = cv2.imread("zebra.jpg")
triangle = numpy.array([[300, 0], [399, 0], [399, 100]])
color = [255, 255, 255] #white
cv2.fillConvexPoly(img, triangle, color)
cv2.imwrite("with_triangle.jpg", img)
For some purposes (blending, inserting into a web-page where the background is unknown etc.) you may want to use an image format which supports alpha-transparency (in your example you are using jpeg, which doesn't) and set the alpha channel to zero:
import cv2
import numpy
img = cv2.imread("zebra.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) #convert to 4-channel image
triangle = numpy.array([[300, 0], [399, 0], [399, 100]])
color = [255, 255, 255, 0] #white with zero alpha
cv2.fillConvexPoly(img, triangle, color)
cv2.imwrite("with_triangle.png", img) #save to PNG for transparency support
The answer above is "hard-coded", yet you have accepted it. You will have to manually change the values to create triangles for different images. Check below.
I have a solution that places a triangle by just varying a single variable var
, depending on how big the triangle has to be. If you want you can fix a single value as well.
Just include var
and alter the next line as shown:
var = 50
triangle = np.array([[img.shape[1] - var, 0], [img.shape[1], 0], [img.shape[1], var]])
Some samples:
Figure 1
Figure 2
Figure 3
Figure 4