Python 裁剪函数后字母模糊/模糊

Python 裁剪函数后字母模糊/模糊,python,opencv,crop,Python,Opencv,Crop,通过将坐标列表保存到数组中,尝试在多个位置裁剪图像后,裁剪区域中的字母变得非常模糊,我无法找出原因 原始图像看起来像 裁剪后的图像看起来像 有关守则如下: import numpy as np import cv2 im2 = cv2.imread('1.jpg') im = im2.copy() gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) thresh = cv2.ad

通过将坐标列表保存到数组中,尝试在多个位置裁剪图像后,裁剪区域中的字母变得非常模糊,我无法找出原因

原始图像看起来像

裁剪后的图像看起来像

有关守则如下:

import numpy as np
import cv2

im2 = cv2.imread('1.jpg')
im = im2.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)


contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)


squares = []

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)

        if  h>28 and h<34:
            rect = (cv2.rectangle(im,(x,y),(x+w,y+h),(255,255,255),3))
            squares.append(cv2.boundingRect(cnt))
            cv2.imwrite('norm1.jpg',im)

crop_img = [[[255, 255, 255] for x in xrange(377)] for x in xrange(377) ]

for s in squares:
    x = s[0]
    y = s[1]
    w = s[2]
    h = s[3]
    img = im[y:y+h,x:x+w]
    for col in range(y,y+h):
        for row in range(x,x+w):
            if img[col - y][row - x].tolist() == [0,0,0]:
                crop_img[col][row] = [0,0,0]
cv2.imwrite("cropped.jpg", np.array(crop_img))
将numpy导入为np
进口cv2
im2=cv2.imread('1.jpg')
im=im2.copy()
灰色=cv2.CVT颜色(im、cv2.COLOR\U BGR2GRAY)
模糊=cv2.高斯模糊(灰色,(5,5),0)
阈值=cv2。自适应阈值(模糊,255,1,1,11,2)
等高线,层次=cv2.findContours(阈值,cv2.RETR\u列表,cv2.CHAIN\u近似值\u简单)
正方形=[]
对于轮廓中的cnt:
如果cv2.轮廓面积(cnt)>50:
[x,y,w,h]=cv2.boundingRect(cnt)
如果h>28和h
输出:

在代码中,哪个变量是第一个,哪个变量是第二个。我也不确定,但请检查您的数据类型是否在某处发生了更改。嗨,阿比德。我不确定“first and second”是什么意思,但我知道我的数据类型在“if img[col-y][row-x].tolist()==[0,0,0]:”行中发生了更改,我不得不使用.tolist函数,因为它抛出了错误:ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()。我希望这能澄清一些问题。谢谢哦对不起,我想问“在你的代码中,哪个变量是你问题中的第一个图像,哪个变量是第二个图像”,没关系!我的代码中的“norm1.jpg”将是第一个图像,“cropped.jpg”将是我的第二个图像@AbidRahmanKRunning您的代码在我的系统中,对于cropped.jpg,我得到一个全白色图像。没有别的了。这是预期的结果吗?
import numpy as np
import cv2
import matplotlib.pyplot as plt

im2 = cv2.imread('norm1_zps89266edb.jpg')
im = im2.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
ret3,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

#we ony want the external contours
contours,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 
#extract the countours with area > 50
squares = [cnt for cnt in contours if cv2.contourArea(cnt) > 50]

#mask array with the same shape as img (but only 1 channel)
mask = np.zeros((im.shape[0], im.shape[1]))
#draw the contours filled with 255 values. 
cv2.drawContours(mask,squares,-1,255,-1)

newImage = np.where(mask==255, thresh, 255)

plt.imshow(newImage)
plt.show()

cv2.imwrite("cropped.jpg", newImage)