Reputation: 348
I have an image whose edge looks super edgy and blocky. I want to anti-aliasing, but as far as I know, with super sampling, I am taking the average color of nearby pixel to make the image looks less jagged and gradient. But I don't really want that. I need the output to be curvy, but without the gradient effect.
I tried to use filter=Image.ANTIALIAS
, which obviously does not help to get what I want.
My input Image:
My output desire:
Does this sound like vectorization, and is this even possible?
Thank you
Upvotes: 2
Views: 942
Reputation: 2940
This answer explains how to smooth a blocky image. The first step is to get the contours for the image. Then, each contour is converted to a list. That list is interpolated so that no two successive points are too far apart. Finally this list of points is smoothed using scipy.signal.savgol_filter()
. Results:
Change the window_length
parameter for more smoothing effect:
import cv2
import numpy as np
import scipy
from scipy import signal
import math
colors = (0,255,0), (255,0,255)
max_dist_between_points = .25
# Get contours
img = cv2.imread('/home/stephen/Desktop/jaggy.png')
gray = 255-cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 123, 123)
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
def distance(a,b): return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
def max_dist(points):
max_dist = 0
for i in range(len(points)-1):
dist = distance(points[i], points[i+1])
if dist > max_dist: max_dist = dist
return max_dist
def interpolate(points):
interpolated = [points[0]]
for i in range(len(points)-1):
a,b = points[i], points[i+1]
dist = distance(a,b)
if dist >= max_dist_between_points:
midpoint = (a[0]+b[0])/2, (a[1]+b[1])/2
interpolated.append(midpoint)
interpolated.append(b)
return interpolated
# Iterate through each contour
for contour in contours:
# Reformat the contour into two lists of X and Y values
points, new_points = list(contour), []
for point in points: new_points.append(tuple(point[0]))
points = new_points
# Interpolate the contour points so that they aren't spread out
while max_dist(points) > 2:
print(len(points))
points = interpolate(points)
X, Y = zip(*points)
# Define smoothing parameters
window_length, polyorder = 155, 3
# Smoooth
X = signal.savgol_filter(X, window_length, polyorder)
Y = signal.savgol_filter(Y, window_length, polyorder)
# Re zip and iterate through the points
smooth = list(zip(X,Y))
for point in range(len(smooth)):
a,b = smooth[point-1], smooth[point]
a,b = tuple(np.array(a, int)), tuple(np.array(b, int))
cv2.line(img, a, b, colors[contours.index(contour)], 2)
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()
Upvotes: 3