如何在python中使用opencv设置图像dpi?

时间:2019-06-08 07:18:34

标签: python-3.x opencv

我正在尝试在python中使用opencv将dpi设置为(72,72)。谁能告诉我如何使用imwrite在opencv中分配dpi?

img = cv2.imread('kitchen.jpeg')
img = cv2.resize(img,(500,500),interpolation=cv2.INTER_AREA)
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (10,10,500,500)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
lower_white = np.array([0, 0, 0], dtype=np.uint8)
upper_white = np.array([0,0,0], dtype=np.uint8)
mask = cv2.inRange(img, lower_white, upper_white) # could also use threshold
res = cv2.bitwise_not(img, img, mask)
cv2.imwrite('kitchen_processed.jpeg',img)

1 个答案:

答案 0 :(得分:0)

emm dpi仅用于打印。在图像写入过程中,您不必执行或无法执行(对于某些格式)。仅在图像打印时才需要这样做。如果您坚持这样做。写入图像后,以文件名作为变量调用System.call

convert -density 75 -units pixelsperinch infile.jpg outfile.png

通常,密度为300或更高。您可以使用75

编辑

添加此内容。不确定是否还有其他潜在问题。但是根据您的标题,添加此行应该可以解决您的问题

import subprocess


img = cv2.imread('kitchen.jpeg')
img = cv2.resize(img,(500,500),interpolation=cv2.INTER_AREA)
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (10,10,500,500)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
lower_white = np.array([0, 0, 0], dtype=np.uint8)
upper_white = np.array([0,0,0], dtype=np.uint8)
mask = cv2.inRange(img, lower_white, upper_white) # could also use threshold
res = cv2.bitwise_not(img, img, mask)
cv2.imwrite('kitchen_processed.png',img)
subprocess.run('convert -density 75 -units pixelsperinch kitchen_processed.png outfile.png')